PKmwMABBxbbg/__init__.py"""Bloomberg data toolkit for humans""" __version__ = '0.1.1' PKOvMcI * *xbbg/assist.pyimport json import os import time import pandas as pd import pdblp from xone import utils, files, logs from xbbg import const from xbbg.conn import with_bloomberg, create_connection from xbbg.timezone import DEFAULT_TZ ELEMENTS = [ 'periodicityAdjustment', 'periodicitySelection', 'currency', 'nonTradingDayFillOption', 'nonTradingDayFillMethod', 'maxDataPoints', 'returnEIDs', 'returnRelativeDate', 'overrideOption', 'pricingOption', 'adjustmentNormal', 'adjustmentAbnormal', 'adjustmentSplit', 'adjustmentFollowDPDF', 'calendarCodeOverride', ] ELEM_KEYS = dict( PeriodAdj='periodicityAdjustment', PerAdj='periodicityAdjustment', Period='periodicitySelection', Per='periodicitySelection', Currency='currency', Curr='currency', FX='currency', Days='nonTradingDayFillOption', Fill='nonTradingDayFillMethod', Points='maxDataPoints', # 'returnEIDs', 'returnRelativeDate', Quote='overrideOption', QuoteType='pricingOption', QtTyp='pricingOption', CshAdjNormal='adjustmentNormal', CshAdjAbnormal='adjustmentAbnormal', CapChg='adjustmentSplit', UseDPDF='adjustmentFollowDPDF', Calendar='calendarCodeOverride', ) ELEM_VALS = dict( periodicityAdjustment=dict( A='ACTUAL', C='CALENDAR', F='FISCAL', ), periodicitySelection=dict( D='DAILY', W='WEEKLY', M='MONTHLY', Q='QUARTERLY', S='SEMI_ANNUALLY', Y='YEARLY' ), nonTradingDayFillOption=dict( N='NON_TRADING_WEEKDAYS', W='NON_TRADING_WEEKDAYS', Weekdays='NON_TRADING_WEEKDAYS', C='ALL_CALENDAR_DAYS', A='ALL_CALENDAR_DAYS', All='ALL_CALENDAR_DAYS', T='ACTIVE_DAYS_ONLY', Trading='ACTIVE_DAYS_ONLY', ), nonTradingDayFillMethod=dict( C='PREVIOUS_VALUE', P='PREVIOUS_VALUE', Previous='PREVIOUS_VALUE', B='NIL_VALUE', Blank='NIL_VALUE', NA='NIL_VALUE', ), overrideOption=dict( A='OVERRIDE_OPTION_GPA', G='OVERRIDE_OPTION_GPA', Average='OVERRIDE_OPTION_GPA', C='OVERRIDE_OPTION_CLOSE', Close='OVERRIDE_OPTION_CLOSE', ), pricingOption=dict( P='PRICING_OPTION_PRICE', Price='PRICING_OPTION_PRICE', Y='PRICING_OPTION_YIELD', Yield='PRICING_OPTION_YIELD', ), ) def _proc_ovrds_(**kwargs): """ Bloomberg overrides Args: **kwargs: overrides Returns: list of tuples """ return [ (k, v) for k, v in kwargs.items() if k not in list(ELEM_KEYS.keys()) + list(ELEM_KEYS.values()) ] def _proc_elms_(**kwargs): """ 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='A', Fill='B') [('nonTradingDayFillOption', 'ALL_CALENDAR_DAYS'), ('nonTradingDayFillMethod', 'NIL_VALUE')] >>> _proc_elms_(CshAdjNormal=False, CshAdjAbnormal=True) [('adjustmentNormal', False), ('adjustmentAbnormal', True)] >>> _proc_elms_(Per='W', Quote='Average', start_date='2018-01-10') [('periodicitySelection', 'WEEKLY'), ('overrideOption', 'OVERRIDE_OPTION_GPA')] >>> _proc_elms_(QuoteType='Y') [('pricingOption', 'PRICING_OPTION_YIELD')] """ return [ (ELEM_KEYS.get(k, k), ELEM_VALS.get(ELEM_KEYS.get(k, k), dict()).get(v, v)) for k, v in kwargs.items() if k in list(ELEM_KEYS.keys()) + list(ELEM_KEYS.values()) ] @with_bloomberg def check_hours(tickers, tz_exch, tz_loc=DEFAULT_TZ): """ Check exchange hours for tickers Args: tickers: list of tickers tz_exch: exchange timezone tz_loc: local timezone Returns: Local and exchange hours """ cols = ['Trading_Day_Start_Time_EOD', 'Trading_Day_End_Time_EOD'] con, _ = create_connection() hours = con.ref(tickers=tickers, flds=cols) cur_dt = pd.Timestamp('today').strftime('%Y-%m-%d ') hours.loc[:, 'local'] = hours.value.astype(str).str[:-3] hours.loc[:, 'exch'] = pd.DatetimeIndex( cur_dt + hours.value.astype(str) ).tz_localize(tz_loc).tz_convert(tz_exch).strftime('%H:%M') hours = pd.concat([ hours.set_index(['ticker', 'field']).exch.unstack().loc[:, cols], hours.set_index(['ticker', 'field']).local.unstack().loc[:, cols], ], axis=1) hours.columns = ['Exch_Start', 'Exch_End', 'Local_Start', 'Local_End'] return hours def _hist_file_(ticker: str, dt: (str, pd.Timestamp), typ='TRADE'): """ 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: >>> data_path = os.environ.get('ROOT_DATA_PATH', '') >>> d_file = _hist_file_(ticker='ES1 Index', dt='2018-08-01') >>> root = f'{data_path}/Index/ES1 Index' >>> if d_file: assert d_file == f'{root}/TRADE/2018-08-01.parq' """ data_path = os.environ.get('ROOT_DATA_PATH', '') if not data_path: return '' asset = ticker.split()[-1] proper_ticker = ticker.replace('/', '_') cur_dt = pd.Timestamp(dt).strftime('%Y-%m-%d') return f'{data_path}/{asset}/{proper_ticker}/{typ}/{cur_dt}.parq' def _ref_file_(ticker: str, fld: str, has_date=False, from_cache=False, ext='parq', **kwargs): """ Data file location for Bloomberg reference data Args: ticker: ticker name fld: field has_date: whether add current date to data file from_cache: if has_date is True, whether to load file from latest cached ext: file extension **kwargs: other overrides passed to ref function Returns: file location Examples: >>> data_path = os.environ.get('ROOT_DATA_PATH', '') >>> d_file = _ref_file_('BLT LN Equity', fld='Crncy') >>> root = f'{data_path}/Equity/BLT LN Equity' >>> if d_file: assert d_file == f'{root}/Crncy/ovrd=None.parq' """ data_path = os.environ.get('ROOT_DATA_PATH', '') if not data_path: return '' proper_ticker = ticker.replace('/', '_') root = f'{data_path}/{ticker.split()[-1]}/{proper_ticker}/{fld}' if len(kwargs) > 0: info = utils.to_str(kwargs)[1:-1] else: info = 'ovrd=None' # Check date info if has_date: cur_files = [] missing = f'{root}/asof={utils.cur_time(trading=False)}, {info}.{ext}' if from_cache: cur_files = files.all_files(path_name=root, keyword=info, ext=ext) if len(cur_files) > 0: upd_dt = [val for val in sorted(cur_files)[-1][:-4].split(', ') if 'asof=' in val] if len(upd_dt) > 0: diff = pd.Timestamp('today') - pd.Timestamp(upd_dt[0].split('=')[-1]) if diff >= pd.Timedelta('10D'): return missing return sorted(cur_files)[-1] else: return missing else: return f'{root}/{info}.{ext}' def _save_intraday_(data: pd.DataFrame, ticker: str, dt: (str, pd.Timestamp), 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] """ cur_dt = pd.Timestamp(dt).strftime('%Y-%m-%d') logger = logs.get_logger(_save_intraday_, level='debug') info = f'{ticker} / {cur_dt} / {typ}' data_file = _hist_file_(ticker=ticker, dt=dt, typ=typ) if not data_file: return if data.empty: logger.warning(f'data is empty for {info} ...') return mkt_info = const.market_info(ticker=ticker) if 'exch' not in mkt_info: logger.error(f'cannot find market info for {ticker} ...') return exch = mkt_info['exch'] end_time = pd.Timestamp( const.market_timing(ticker=ticker, dt=dt, timing='FINISHED') ).tz_localize(exch.tz) now = pd.Timestamp('now', tz=exch.tz) - pd.Timedelta('1H') if end_time > now: logger.debug(f'skip saving cause market close ({end_time}) < now - 1H ({now}) ...') return logger.info(f'saving data to {data_file} ...') files.create_folder(data_file, is_file=True) data.to_parquet(data_file) def _query_(con, func: str, **kwargs): """ Make Bloomberg query with active connection to save time Args: con: Bloomberg active connection func: function name **kwargs: to be passed to query Returns: pd.DataFrame: query result """ if isinstance(con, pdblp.BCon): if con.debug: con.debug = False return getattr(con, func)(**kwargs) else: with pdblp.bopen(port=8194, timeout=5000) as bb: return getattr(bb, func)(**kwargs) def current_missing(**kwargs): """ Check number of trials for missing values Returns: dict """ data_path = os.environ.get('ROOT_DATA_PATH', '') empty_log = f'{data_path}/Logs/EmptyQueries.json' if not files.exists(empty_log): return 0 with open(empty_log, 'r') as fp: cur_miss = json.load(fp=fp) return cur_miss.get(info_key(**kwargs), 0) def update_missing(**kwargs): """ Update number of trials for missing values Returns: dict """ key = info_key(**kwargs) data_path = os.environ.get('ROOT_DATA_PATH', '') empty_log = f'{data_path}/Logs/EmptyQueries.json' cur_miss = dict() if files.exists(empty_log): with open(empty_log, 'r') as fp: cur_miss = json.load(fp=fp) cur_miss[key] = cur_miss.get(key, 0) + 1 while not os.access(empty_log, os.W_OK): time.sleep(1) else: with open(empty_log, 'w') as fp: json.dump(cur_miss, fp=fp, indent=2) return cur_miss def info_key(ticker: str, dt: (str, pd.Timestamp), typ='TRADE', **kwargs): """ Generate key from given info Args: ticker: ticker name dt: date to download typ: [TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK] **kwargs: other kwargs Returns: str """ return utils.to_str(dict( ticker=ticker, dt=pd.Timestamp(dt).strftime('%Y-%m-%d'), typ=typ, **kwargs )) if __name__ == '__main__': """ CommandLine: python -m xbbg.assit all """ import xdoctest xdoctest.doctest_module(__file__) PKvM~== xbbg/blp.pyimport pandas as pd from itertools import product from xone import utils, files, logs from xbbg import const, intervals, assist from xbbg.conn import with_bloomberg, create_connection from xbbg.timezone import DEFAULT_TZ from xbbg.exchange import TradingHours, SessNA @with_bloomberg def bdp(tickers: (str, list), flds: (str, list), cache=False, **kwargs): """ Get reference data and save to Args: tickers: tickers flds: fields to query cache: bool - use cache to store data **kwargs: overrides Returns: pd.DataFrame Examples: >>> bdp('IQ US Equity', 'Crncy') ticker field value 0 IQ US Equity Crncy USD """ logger = logs.get_logger(bdp) tickers = utils.flatten(tickers) flds = utils.flatten(flds) con, _ = create_connection() ovrds = assist._proc_ovrds_(**kwargs) if not cache: full_list = '\n'.join([f'tickers: {tickers[:8]}'] + [ f' {tickers[n:(n + 8)]}' for n in range(8, len(tickers), 8) ]) logger.info(f'reference data for\n{full_list}\nfields: {flds}') return con.ref(tickers=tickers, flds=flds, ovrds=ovrds) cached_data = [] cur_data, ref_data = pd.DataFrame(), pd.DataFrame() has_date = kwargs.pop('has_date', False) from_cache = kwargs.pop('from_cache', False) loaded = pd.DataFrame(data=0, index=tickers, columns=flds) for ticker, fld in product(tickers, flds): data_file = assist._ref_file_( ticker=ticker, fld=fld, has_date=has_date, from_cache=from_cache, **kwargs ) if files.exists(data_file): cached_data.append(pd.read_parquet(data_file)) loaded.loc[ticker, fld] = 1 to_qry = loaded.where(loaded == 0).dropna(how='all', axis=1).dropna(how='all', axis=0) if not to_qry.empty: ref_tcks = to_qry.index.tolist() ref_flds = to_qry.columns.tolist() full_list = '\n'.join([f'tickers: {ref_tcks[:8]}'] + [ f' {ref_tcks[n:(n + 8)]}' for n in range(8, len(ref_tcks), 8) ]) logger.info(f'loading reference data for\n{full_list}\nfields: {ref_flds}') ref_data = con.ref(tickers=ref_tcks, flds=ref_flds, ovrds=ovrds) for r, snap in ref_data.iterrows(): subset = [r] data_file = assist._ref_file_(ticker=snap.ticker, fld=snap.field, **kwargs) if data_file: files.create_folder(data_file, is_file=True) ref_data.iloc[subset].to_parquet(data_file) cached_data.append(ref_data.iloc[subset]) if len(cached_data) == 0: return pd.DataFrame() return pd.DataFrame( pd.concat(cached_data, sort=False) ).reset_index(drop=True).drop_duplicates(subset=['ticker', 'field'], keep='last') @with_bloomberg def bdh( tickers: (str, list), flds: (str, list), start_date: (str, pd.Timestamp), end_date: (str, pd.Timestamp), **kwargs ): """ Bloomberg historical data Args: tickers: ticker(s) flds: field(s) start_date: start date end_date: end date **kwargs: overrides Returns: pd.DataFrame Examples: >>> flds = ['High', 'Low', 'Last_Price'] >>> s_dt, e_dt = '2018-02-05', '2018-02-08' >>> d = bdh('VIX Index', flds, start_date=s_dt, end_date=e_dt).round(2) >>> d.index.name = None >>> r = d.transpose() >>> r.index.names = (None, None) >>> r 2018-02-05 2018-02-06 2018-02-07 2018-02-08 VIX Index High 38.80 50.30 31.64 36.17 Low 16.80 22.42 21.17 24.41 Last_Price 37.32 29.98 27.73 33.46 """ logger = logs.get_logger(bdh) con, _ = create_connection() elms = assist._proc_elms_(**kwargs) ovrds = assist._proc_ovrds_(**kwargs) if isinstance(tickers, str): tickers = [tickers] if isinstance(flds, str): flds = [flds] s_dt = utils.fmt_dt(start_date, fmt='%Y-%m-%d') e_dt = utils.fmt_dt(end_date, fmt='%Y-%m-%d') full_list = '\n'.join([f'tickers: {tickers[:8]}'] + [ f' {tickers[n:(n + 8)]}' for n in range(8, len(tickers), 8) ]) logger.info(f'loading historical data for\n{full_list}\nfields: {flds}') return con.bdh( tickers=tickers, flds=flds, elms=elms, ovrds=ovrds, start_date=s_dt.replace('-', ''), end_date=e_dt.replace('-', ''), ) @with_bloomberg def bds(tickers: (str, list), flds: (str, list), cached=False, **kwargs): """ Download block data from Bloomberg Args: tickers: ticker(s) flds: field(s) cached: whether read from cached **kwargs: other overrides for query Returns: pd.DataFrame: block data Examples: >>> pd.options.display.width = 120 >>> s_dt, e_dt = '20180301', '20181031' >>> dvd = bds('NVDA US Equity', 'DVD_Hist_All', DVD_Start_Dt=s_dt, DVD_End_Dt=e_dt) >>> dvd.loc[:, ['ticker', 'name', 'value']] ticker name value 0 NVDA US Equity Declared Date 2018-08-16 1 NVDA US Equity Ex-Date 2018-08-29 2 NVDA US Equity Record Date 2018-08-30 3 NVDA US Equity Payable Date 2018-09-21 4 NVDA US Equity Dividend Amount 0.15 5 NVDA US Equity Dividend Frequency Quarter 6 NVDA US Equity Dividend Type Regular Cash 7 NVDA US Equity Declared Date 2018-05-10 8 NVDA US Equity Ex-Date 2018-05-23 9 NVDA US Equity Record Date 2018-05-24 10 NVDA US Equity Payable Date 2018-06-15 11 NVDA US Equity Dividend Amount 0.15 12 NVDA US Equity Dividend Frequency Quarter 13 NVDA US Equity Dividend Type Regular Cash """ logger = logs.get_logger(bds) tickers = utils.flatten(tickers, unique=True) flds = utils.flatten(flds, unique=True) con, _ = create_connection() ovrds = assist._proc_ovrds_(**kwargs) if not cached: return con.bulkref(tickers=tickers, flds=flds, ovrds=ovrds) cache_data = [] loaded = pd.DataFrame(data=0, index=tickers, columns=flds) for ticker, fld in product(tickers, flds): data_file = assist._ref_file_( ticker=ticker, fld=fld, has_date=True, from_cache=cached, ext='pkl', **kwargs ) logger.debug(f'checking file: {data_file}') if files.exists(data_file): logger.debug('[YES]') cache_data.append(pd.read_pickle(data_file)) loaded.loc[ticker, fld] = 1 logger.debug(f'\n{loaded.to_string()}') to_qry = loaded.where(loaded == 0).dropna(how='all', axis=1).dropna(how='all', axis=0) if not to_qry.empty: ref_tcks = to_qry.index.tolist() ref_flds = to_qry.columns.tolist() full_list = '\n'.join([f'tickers: {ref_tcks[:8]}'] + [ f' {ref_tcks[n:(n + 8)]}' for n in range(8, len(ref_tcks), 8) ]) logger.info(f'loading block data for\ntickers: {full_list}\nfields: {ref_flds}') data = con.bulkref(tickers=ref_tcks, flds=ref_flds, ovrds=ovrds) for (ticker, fld), grp in data.groupby(['ticker', 'field']): data_file = assist._ref_file_( ticker=ticker, fld=fld, has_date=True, ext='pkl', **kwargs ) if data_file: files.create_folder(data_file, is_file=True) grp.reset_index(drop=True).to_pickle(data_file) if to_qry.loc[ticker, fld] == 0: cache_data.append(grp) if len(cache_data) == 0: return pd.DataFrame() return pd.concat(cache_data, sort=False).reset_index(drop=True) @with_bloomberg def bdib(ticker: (str, list), dt: (str, pd.Timestamp), typ='TRADE', batch=False): """ Download intraday data and save to cache Args: ticker: ticker name dt: date to download typ: [TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK] batch: whether is batch process to download data Returns: pd.DataFrame """ logger = logs.get_logger(bdib) t_1 = pd.Timestamp('today').date() - pd.Timedelta('1D') whole_day = pd.Timestamp(dt).date() < t_1 if (not whole_day) and batch: logger.warning(f'querying date {t_1} is too close, ignoring download ...') return None cur_dt = pd.Timestamp(dt).strftime('%Y-%m-%d') asset = ticker.split()[-1] data_file = assist._hist_file_(ticker=ticker, dt=dt, typ=typ) info_log = f'{ticker} / {cur_dt} / {typ}' if files.exists(data_file): if batch: return logger.info(f'reading from {data_file} ...') return pd.read_parquet(data_file) if asset in ['Equity', 'Curncy', 'Index', 'Comdty']: info = const.market_info(ticker=ticker) if any(k not in info for k in ['exch']): logger.warning(f'cannot find market info for {ticker}: {utils.to_str(info)}') return pd.DataFrame() exch = info['exch'] assert isinstance(exch, TradingHours), ValueError( f'exch info for {ticker} is not TradingHours: {exch}' ) else: logger.error(f'unknown asset type: {asset}') return pd.DataFrame() time_fmt = '%Y-%m-%dT%H:%M:%S' time_idx = pd.DatetimeIndex([ f'{cur_dt} {exch.hours.allday.start_time}', f'{cur_dt} {exch.hours.allday.end_time}'] ).tz_localize(exch.tz).tz_convert(DEFAULT_TZ).tz_convert('UTC') if time_idx[0] > time_idx[1]: time_idx -= pd.TimedeltaIndex(['1D', '0D']) q_tckr = ticker if info.get('is_fut', False): if 'freq' not in info: logger.error(f'[freq] missing in info for {info_log} ...') is_sprd = info.get('has_sprd', False) and (len(ticker[:-1]) != info['tickers'][0]) if not is_sprd: q_tckr = fut_ticker(gen_ticker=ticker, dt=dt, freq=info['freq']) if q_tckr == '': logger.error(f'cannot find futures ticker for {ticker} ...') return pd.DataFrame() info_log = f'{q_tckr} / {cur_dt} / {typ}' cur_miss = assist.current_missing(ticker=ticker, dt=dt, typ=typ, func=bdib.__name__) if cur_miss >= 2: if batch: return logger.info(f'{cur_miss} trials with no data {info_log}') return pd.DataFrame() logger.info(f'loading data for {info_log} ...') con, _ = create_connection() data = con.bdib( ticker=q_tckr, event_type=typ, interval=1, start_datetime=time_idx[0].strftime(time_fmt), end_datetime=time_idx[1].strftime(time_fmt), ) assert isinstance(data, pd.DataFrame) if data.empty: logger.warning(f'no data for {info_log} ...') assist.update_missing(ticker=ticker, dt=dt, typ=typ, func=bdib.__name__) return pd.DataFrame() data = data.tz_localize('UTC').tz_convert(exch.tz) assist._save_intraday_(data=data, ticker=ticker, dt=dt, typ=typ) return None if batch else data def intraday( ticker: (str, list), dt: (str, pd.Timestamp), session='', start_time=None, end_time=None, typ='TRADE' ): """ Retrieve interval data for ticker Args: ticker: ticker dt: date session: examples include day_open_30, am_normal_30_30, day_close_30, allday_exact_0930_1000 start_time: start time end_time: end time typ: [TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK] Returns: pd.DataFrame """ cur_data = bdib(ticker=ticker, dt=dt, typ=typ) if cur_data.empty: return pd.DataFrame() fmt = '%H:%M:%S' ss = SessNA if session: ss = intervals.get_interval(ticker=ticker, session=session) if ss != SessNA: start_time = pd.Timestamp(ss.start_time).strftime(fmt) end_time = pd.Timestamp(ss.end_time).strftime(fmt) if start_time and end_time: return cur_data.between_time(start_time=start_time, end_time=end_time) return cur_data @with_bloomberg def active_futures(ticker: str, dt): """ 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] info = const.market_info(f'{prefix[:-1]}1 {asset}') f1, f2 = f'{prefix[:-1]}1 {asset}', f'{prefix[:-1]}2 {asset}' fut_2 = fut_ticker(gen_ticker=f2, dt=dt, freq=info['freq']) fut_1 = fut_ticker(gen_ticker=f1, dt=dt, freq=info['freq']) fut_tk = bdp(tickers=[fut_1, fut_2], flds='Last_Tradeable_Dt', cache=True) if pd.Timestamp(dt).month < pd.Timestamp(fut_tk.value[0]).month: return fut_1 d1 = bdib(ticker=f1, dt=dt) d2 = bdib(ticker=f2, dt=dt) return fut_1 if d1.volume.sum() > d2.volume.sum() else fut_2 @with_bloomberg def fut_ticker(gen_ticker: str, dt, freq: str): """ Get proper ticker from generic ticker Args: gen_ticker: generic ticker dt: date freq: futures contract frequency Returns: str: exact futures ticker """ logger = logs.get_logger(fut_ticker) dt = pd.Timestamp(dt) t_info = gen_ticker.split() asset = t_info[-1] if asset in ['Index', 'Curncy', 'Comdty']: ticker = ' '.join(t_info[:-1]) prefix, idx, postfix = ticker[:-1], int(ticker[-1]) - 1, asset elif asset == 'Equity': ticker = t_info[0] prefix, idx, postfix = ticker[:-1], int(ticker[-1]) - 1, ' '.join(t_info[1:]) else: logger.error(f'unkonwn asset type for ticker: {gen_ticker}') return '' month_ext = 4 if asset == 'Comdty' else 2 months = pd.DatetimeIndex(start=dt, periods=max(idx + month_ext, 3), freq=freq) logger.debug(f'pulling expiry dates for months: {months}') def to_fut(month): return prefix + const.Futures[month.strftime('%b')] + \ month.strftime('%y')[-1] + ' ' + postfix fut = [to_fut(m) for m in months] logger.debug(f'trying futures: {fut}') # noinspection PyBroadException try: fut_matu = bdp(tickers=fut, flds='last_tradeable_dt', cache=True) except Exception as e1: logger.error(f'error downloading futures contracts (1st trial) {e1}:\n{fut}') # noinspection PyBroadException try: fut = fut[:-1] logger.debug(f'trying futures (2nd trial): {fut}') fut_matu = bdp(tickers=fut, flds='last_tradeable_dt', cache=True) except Exception as e2: logger.error(f'error downloading futures contracts (2nd trial) {e2}:\n{fut}') return '' sub_fut = fut_matu[pd.DatetimeIndex(fut_matu.value) > dt] logger.debug(f'futures full chain:\n{fut_matu.to_string()}') logger.debug(f'getting index {idx} from:\n{sub_fut.to_string()}') return sub_fut.ticker.values[idx] if __name__ == '__main__': """ CommandLine: python -m xbbg.blp all """ import xdoctest xdoctest.doctest_module(__file__) PKvM'8SS xbbg/conn.pyimport pdblp from functools import wraps def with_bloomberg(func): """ Wrapper function for Bloomberg connection Args: func: function to wrap """ @wraps(func) def wrapper(*args, **kwargs): con, new = create_connection() res = func(*args, **kwargs) if new: delete_connection() return res return wrapper def create_connection(): """ Create Bloomberg connection Returns: (Bloomberg connection, if connection is new) """ if '_xcon_' in globals(): con = globals()['_xcon_'] assert isinstance(con, pdblp.BCon) if getattr(con, '_session').start(): con.start() return con, False else: con = pdblp.BCon(port=8194, timeout=5000) globals()['_xcon_'] = con con.start() return con, True def delete_connection(): """ Stop and destroy Bloomberg connection """ if '_xcon_' in globals(): con = globals().pop('_xcon_') if not getattr(con, '_session').start(): con.stop() PK)\uMZ3FF xbbg/const.pyimport pandas as pd from xbbg import timezone from xbbg.asset.equity import Equity from xbbg.asset.curncy import Curncy from xbbg.asset.comdty import Comdty from xbbg.asset.index import Index from xbbg.asset.corp import Corp from collections import namedtuple CurrencyPair = namedtuple('CurrencyPair', ['ticker', 'factor', 'reversal']) Futures = dict( Jan='F', Feb='G', Mar='H', Apr='J', May='K', Jun='M', Jul='N', Aug='Q', Sep='U', Oct='V', Nov='X', Dec='Z', ) Currencies = { 'AUDUSD': CurrencyPair('AUD Curncy', 1., -1), 'JPYUSD': CurrencyPair('JPY Curncy', 1., 1), 'KRWUSD': CurrencyPair('KRW Curncy', 1., 1), 'KWN+1MUSD': CurrencyPair('KRW+1M Curncy', 1., 1), 'TWDUSD': CurrencyPair('TWD Curncy', 1., 1), 'NTN+1MUSD': CurrencyPair('NTN+1M Curncy', 1., 1), 'CNYHKD': CurrencyPair('CNYHKD Curncy', 1., -1), 'CNHHKD': CurrencyPair('CNHHKD Curncy', 1., -1), 'HKDUSD': CurrencyPair('HKD Curncy', 1., 1), 'EURUSD': CurrencyPair('EUR Curncy', 1., -1), 'GBPUSD': CurrencyPair('GBP Curncy', 1., -1), 'GBpUSD': CurrencyPair('GBP Curncy', 100., -1), 'GBPAUD': CurrencyPair('GBPAUD Curncy', 1., -1), 'GBpAUD': CurrencyPair('GBPAUD Curncy', 100., -1), 'GBPEUR': CurrencyPair('GBPEUR Curncy', 1., -1), 'GBpEUR': CurrencyPair('GBPEUR Curncy', 100., -1), 'GBPHKD': CurrencyPair('GBPHKD Curncy', 1., -1), 'GBpHKD': CurrencyPair('GBPHKD Curncy', 100., -1), 'INT1USD': CurrencyPair('INT1 Curncy', 1., 1), 'INT2USD': CurrencyPair('INT2 Curncy', 1., 1), 'IRD1USD': CurrencyPair('IRD1 Curncy', 10000., -1), 'IRD2USD': CurrencyPair('IRD2 Curncy', 10000., -1), 'XID1USD': CurrencyPair('XID1 Curncy', 10000., -1), 'XID2USD': CurrencyPair('XID2 Curncy', 10000., -1), } def market_info(ticker: str): """ Get info for given market Args: ticker: Bloomberg full ticker Returns: dict Examples: >>> from xbbg.exchange import TradingHours >>> >>> info = market_info('SHCOMP Index')['exch'] >>> isinstance(info, TradingHours) True >>> info.tz 'Asia/Shanghai' >>> info = market_info('CL1 Comdty') >>> info['freq'], info['is_fut'] ('M', True) """ t_info = ticker.split() # ========================== # # Equity # # ========================== # if (t_info[-1] == 'Equity') and ('=' not in t_info[0]): exch = t_info[-2] for info in Equity: if 'exch_codes' not in info: continue if exch in info['exch_codes']: return info.copy() else: return dict() # ============================ # # Currency # # ============================ # if t_info[-1] == 'Curncy': for info in Curncy: if 'tickers' not in info: continue if (t_info[0].split('+')[0] in info['tickers']) or \ (t_info[0][-1].isdigit() and (t_info[0][:-1] in info['tickers'])): return info.copy() else: return dict() if t_info[-1] == 'Comdty': for info in Comdty: if 'tickers' not in info: continue if t_info[0][:-1] in info['tickers']: return info.copy() else: return dict() # =================================== # # Index / Futures # # =================================== # if (t_info[-1] == 'Index') or ( (t_info[-1] == 'Equity') and ('=' in t_info[0]) ): if t_info[-1] == 'Equity': tck = t_info[0].split('=')[0] else: tck = ' '.join(t_info[:-1]) for info in Index: if 'tickers' not in info: continue if (tck[:2] == 'UX') and ('UX' in info['tickers']): return info.copy() if tck in info['tickers']: if t_info[-1] == 'Equity': return info.copy() if not info.get('is_fut', False): return info.copy() if tck[:-1].rstrip() in info['tickers']: if info.get('is_fut', False): return info.copy() else: return dict() if t_info[-1] == 'Corp': for info in Corp: if 'ticker' not in info: continue return dict() def ccy_pair(local, base='USD'): """ 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, reversal=1) >>> ccy_pair(local='GBp') CurrencyPair(ticker='GBP Curncy', factor=100.0, reversal=-1) >>> ccy_pair(local='USD', base='GBp') CurrencyPair(ticker='GBP Curncy', factor=0.01, reversal=1) """ if f'{local}{base}' in Currencies: return Currencies[f'{local}{base}'] elif f'{base}{local}' in Currencies: rev = Currencies[f'{base}{local}'] return CurrencyPair( ticker=rev.ticker, factor=1. / rev.factor, reversal=-rev.reversal ) else: raise NameError(f'incorrect currency - local {local} / base {base}') def market_timing(ticker, dt, timing='EOD', tz='local'): """ 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 JT Equity', dt='2018-09-10') '2018-09-10 14:58' >>> market_timing('7267 JT Equity', dt='2018-09-10', tz=timezone.TimeZone.NY) '2018-09-10 01:58:00-04:00' >>> market_timing('7267 JT Equity', dt='2018-01-10', tz='NY') '2018-01-10 00:58:00-05:00' >>> market_timing('7267 JT Equity', dt='2018-09-10', tz='SPX Index') '2018-09-10 01:58:00-04:00' """ info = market_info(ticker=ticker).get('exch', None) if info is None: raise LookupError(f'No [exch] info found in {ticker} ...') if timing == 'BOD': mkt_time = info.hours.day.start_time elif timing == 'FINISHED': mkt_time = info.hours.allday.end_time else: mkt_time = info.hours.day.end_time cur_dt = pd.Timestamp(str(dt)).strftime('%Y-%m-%d') if tz == 'local': return f'{cur_dt} {mkt_time}' return timezone.tz_convert(f'{cur_dt} {mkt_time}', to_tz=tz, from_tz=info.tz) if __name__ == '__main__': """ CommandLine: python -m xbbg.const all """ import xdoctest xdoctest.doctest_module(__file__) PKMuM;O77xbbg/exchange.pyfrom collections import namedtuple from xbbg.timezone import TimeZone Session = namedtuple('Session', ['start_time', 'end_time']) MarketSessions = namedtuple('MarketSessions', [ 'allday', 'day', 'am', 'pm', 'night', 'pre', 'post', ]) TradingHours = namedtuple('TradingHours', ['hours', 'tz']) SessNA = Session(None, None) class ExchHours(dict): """ Exchange market hours """ # ========================== # # Equity # # ========================== # EquityAustralia = TradingHours( hours=MarketSessions( allday=Session('09:59', '16:16'), day=Session('10:00', '16:00'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=Session('16:01', '16:16'), ), tz=TimeZone.AU, ) EquityJapan = TradingHours( hours=MarketSessions( allday=Session('09:00', '15:45'), day=Session('09:01', '14:58'), am=Session('09:01', '11:30'), pm=Session('12:30', '14:58'), night=SessNA, pre=Session('09:00', '09:00'), post=Session('14:59', '15:45'), ), tz=TimeZone.JP, ) EquitySouthKorea = TradingHours( hours=MarketSessions( allday=Session('09:00', '15:35'), day=Session('09:00', '15:20'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=Session('15:21', '15:35'), ), tz=TimeZone.SK, ) EquityTaiwan = TradingHours( hours=MarketSessions( allday=Session('09:00', '13:35'), day=Session('09:00', '13:25'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=Session('13:26', '13:35'), ), tz=TimeZone.TW, ) EquityHongKong = TradingHours( hours=MarketSessions( allday=Session('09:15', '16:15'), day=Session('09:30', '16:00'), am=Session('09:30', '12:00'), pm=Session('13:00', '16:00'), night=SessNA, pre=Session('09:15', '09:30'), post=Session('16:01', '16:15'), ), tz=TimeZone.HK, ) EquityChina = TradingHours( hours=MarketSessions( allday=Session('09:15', '15:05'), day=Session('09:30', '15:00'), am=Session('09:30', '11:30'), pm=Session('13:00', '15:00'), night=SessNA, pre=Session('09:15', '09:30'), post=SessNA, ), tz=TimeZone.SH, ) EquityIndia = TradingHours( hours=MarketSessions( allday=Session('09:00', '17:10'), day=Session('09:00', '15:30'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=Session('15:31', '17:10'), ), tz=TimeZone.IN, ) EquityLondon = TradingHours( hours=MarketSessions( allday=Session('08:00', '17:00'), day=Session('08:00', '16:30'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=Session('16:31', '17:00'), ), tz=TimeZone.UK, ) EquityDublin = TradingHours( hours=MarketSessions( allday=Session('08:00', '17:00'), day=Session('08:00', '16:30'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=Session('16:31', '17:00'), ), tz=TimeZone.UK, ) EquityAmsterdam = TradingHours( hours=MarketSessions( allday=Session('08:00', '17:00'), day=Session('08:00', '16:30'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=Session('16:31', '17:00'), ), tz=TimeZone.UK, ) EquitySpain = TradingHours( hours=MarketSessions( allday=Session('08:00', '17:00'), day=Session('08:00', '16:30'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=Session('16:31', '17:00'), ), tz=TimeZone.UK, ) EquityFrance = TradingHours( hours=MarketSessions( allday=Session('08:00', '17:00'), day=Session('08:00', '16:30'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=Session('16:31', '17:00'), ), tz=TimeZone.UK, ) EquityUS = TradingHours( hours=MarketSessions( allday=Session('04:00', '20:00'), day=Session('09:30', '16:00'), am=SessNA, pm=SessNA, night=SessNA, pre=Session('04:00', '09:30'), post=Session('16:01', '20:00'), ), tz=TimeZone.NY, ) # ============================ # # Currency # # ============================ # CurrencyGeneric = TradingHours( hours=MarketSessions( allday=Session('17:01', '17:00'), day=Session('17:01', '17:00'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=SessNA, ), tz=TimeZone.NY, ) CurrencySouthKorea = TradingHours( hours=MarketSessions( allday=Session('09:00', '15:30'), day=Session('09:00', '15:30'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=SessNA, ), tz=TimeZone.SK, ) CurrencyTaiwan = TradingHours( hours=MarketSessions( allday=Session('09:00', '16:00'), day=Session('09:00', '16:00'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=SessNA, ), tz=TimeZone.TW, ) CurrencyChina = TradingHours( hours=MarketSessions( allday=Session('09:30', '23:30'), day=Session('09:30', '23:30'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=SessNA, ), tz=TimeZone.SH, ) CurrencyIndia = TradingHours( hours=MarketSessions( allday=Session('09:00', '17:00'), day=Session('09:00', '17:00'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=SessNA, ), tz=TimeZone.IN, ) CurrencyDubai = TradingHours( hours=MarketSessions( allday=Session('07:00', '23:59'), day=Session('07:00', '23:59'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=SessNA, ), tz=TimeZone.DB, ) CurrencySingapore = TradingHours( hours=MarketSessions( allday=Session('19:50', '19:35'), day=Session('07:25', '19:35'), am=SessNA, pm=SessNA, night=Session('19:50', '04:45'), pre=SessNA, post=SessNA, ), tz=TimeZone.SG, ) CurrencyICE = TradingHours( hours=MarketSessions( allday=Session('18:30', '17:30'), day=Session('18:30', '17:30'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=SessNA, ), tz=TimeZone.NY, ) # =================================== # # Index / Futures # # =================================== # EquityFuturesIndia = TradingHours( hours=MarketSessions( allday=Session('09:15', '16:45'), day=Session('09:15', '15:30'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=Session('15:31', '16:45'), ), tz=TimeZone.IN, ) IndexFuturesIndia = TradingHours( hours=MarketSessions( allday=Session('09:15', '15:30'), day=Session('09:15', '15:30'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=SessNA, ), tz=TimeZone.IN, ) FuturesAustralia = TradingHours( hours=MarketSessions( allday=Session('17:10', '16:30'), day=Session('09:50', '16:30'), am=SessNA, pm=SessNA, night=Session('17:10', '07:00'), pre=SessNA, post=SessNA, ), tz=TimeZone.AU, ) IndexAustralia = TradingHours( hours=MarketSessions( allday=Session('10:00', '16:20'), day=Session('10:00', '16:20'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=SessNA, ), tz=TimeZone.AU, ) FuturesJapan = TradingHours( hours=MarketSessions( allday=Session('16:30', '15:15'), day=Session('08:45', '15:15'), am=SessNA, pm=SessNA, night=Session('16:30', '05:30'), pre=SessNA, post=SessNA, ), tz=TimeZone.JP, ) FuturesSouthKorea = TradingHours( hours=MarketSessions( allday=Session('18:00', '15:45'), day=Session('09:00', '15:45'), am=SessNA, pm=SessNA, night=Session('18:00', '05:00'), pre=SessNA, post=SessNA, ), tz=TimeZone.SK, ) IndexSouthKorea = TradingHours( hours=MarketSessions( allday=Session('08:30', '15:35'), day=Session('09:00', '15:20'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=Session('15:21', '15:35'), ), tz=TimeZone.SK, ) FuturesTaiwan = TradingHours( hours=MarketSessions( allday=Session('14:15', '13:50'), day=Session('08:45', '13:50'), am=SessNA, pm=SessNA, night=Session('14:15', '04:50'), pre=SessNA, post=SessNA, ), tz=TimeZone.TW, ) FuturesHongKong = TradingHours( hours=MarketSessions( allday=Session('17:15', '01:00'), day=Session('09:15', '16:30'), am=SessNA, pm=SessNA, night=Session('17:15', '01:00'), pre=SessNA, post=SessNA, ), tz=TimeZone.HK, ) FuturesSingapore = TradingHours( hours=MarketSessions( allday=Session('17:00', '04:45'), day=Session('09:00', '16:35'), am=SessNA, pm=SessNA, night=Session('17:00', '04:45'), pre=SessNA, post=SessNA, ), tz=TimeZone.SG, ) IndexLondon = TradingHours( hours=MarketSessions( allday=Session('08:00', '16:35'), day=Session('08:00', '16:30'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=Session('16:31', '16:35'), ), tz=TimeZone.UK, ) IndexEurope1 = TradingHours( hours=MarketSessions( allday=Session('08:00', '17:00'), day=Session('08:00', '17:00'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=SessNA, ), tz=TimeZone.UK, ) IndexEurope2 = TradingHours( hours=MarketSessions( allday=Session('08:00', '17:15'), day=Session('08:00', '17:15'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=SessNA, ), tz=TimeZone.UK, ) IndexEurope3 = TradingHours( hours=MarketSessions( allday=Session('08:00', '18:30'), day=Session('08:00', '18:30'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=SessNA, ), tz=TimeZone.UK, ) IndexUS = TradingHours( hours=MarketSessions( allday=Session('09:30', '16:00'), day=Session('09:30', '16:00'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=SessNA, ), tz=TimeZone.NY, ) CME = TradingHours( hours=MarketSessions( allday=Session('18:00', '17:00'), day=Session('08:00', '17:00'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=SessNA, ), tz=TimeZone.NY, ) FuturesFinancialsICE = TradingHours( hours=MarketSessions( allday=Session('01:00', '21:00'), day=Session('01:00', '21:00'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=SessNA, ), tz=TimeZone.UK, ) FuturesNYFICE = TradingHours( hours=MarketSessions( allday=Session('20:00', '18:00'), day=Session('20:00', '18:00'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=SessNA, ), tz=TimeZone.NY, ) IndexVIX = TradingHours( hours=MarketSessions( allday=Session('03:00', '16:30'), day=Session('03:15', '16:30'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=SessNA, ), tz=TimeZone.NY, ) FuturesCBOE = TradingHours( hours=MarketSessions( allday=Session('18:00', '17:00'), day=Session('18:00', '17:00'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=SessNA, ), tz=TimeZone.NY, ) IndexYieldCurve = TradingHours( hours=MarketSessions( allday=Session('18:00', '17:20'), day=Session('18:00', '17:20'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=SessNA, ), tz=TimeZone.NY, ) # =============================== # # Commodities # # =============================== # NYME = TradingHours( hours=MarketSessions( allday=Session('18:00', '17:00'), day=Session('18:00', '17:00'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=SessNA, ), tz=TimeZone.NY, ) FuturesEuropeICE = TradingHours( hours=MarketSessions( allday=Session('01:00', '23:00'), day=Session('01:00', '23:00'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=SessNA, ), tz=TimeZone.UK, ) CMX = TradingHours( hours=MarketSessions( allday=Session('18:00', '17:00'), day=Session('18:00', '17:00'), am=SessNA, pm=SessNA, night=SessNA, pre=SessNA, post=SessNA, ), tz=TimeZone.NY, ) CommoditiesShanghai = TradingHours( hours=MarketSessions( allday=Session('21:00', '15:00'), day=Session('09:00', '15:00'), am=Session('09:00', '11:30'), pm=Session('13:30', '15:00'), night=Session('21:00', '23:00'), pre=SessNA, post=SessNA, ), tz=TimeZone.SH, ) CommoditiesDalian = TradingHours( hours=MarketSessions( allday=Session('21:00', '15:00'), day=Session('09:00', '15:00'), am=Session('09:00', '11:30'), pm=Session('13:30', '15:00'), night=Session('21:00', '23:30'), pre=SessNA, post=SessNA, ), tz=TimeZone.SH, ) PK\uM"yyxbbg/intervals.pyimport pandas as pd import numpy as np from xone import logs from xbbg import const from xbbg.exchange import Session, SessNA ValidSessions = ['allday', 'day', 'am', 'pm', 'night'] def get_interval(ticker, 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', end_time='09:30') >>> get_interval('005490 KS Equity', 'day_normal_30_20') Session(start_time='09:31', end_time='15:00') >>> get_interval('005490 KS Equity', 'day_close_20') Session(start_time='15:01', end_time='15:20') >>> get_interval('700 HK Equity', 'am_open_30') Session(start_time='09:30', end_time='10:00') >>> get_interval('700 HK Equity', 'am_normal_30_30') Session(start_time='10:01', end_time='11:30') >>> get_interval('700 HK Equity', 'am_close_30') Session(start_time='11:31', end_time='12:00') >>> get_interval('ES1 Index', 'day_exact_2130_2230') Session(start_time=None, end_time=None) >>> get_interval('ES1 Index', 'allday_exact_2130_2230') Session(start_time='21:30', end_time='22:30') >>> get_interval('ES1 Index', 'allday_exact_2130_0230') Session(start_time='21:30', end_time='02:30') """ interval = Intervals(ticker=ticker) ss_info = session.split('_') return getattr(interval, f'market_{ss_info.pop(1)}')(*ss_info) def shift_time(start_time, mins): """ 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(mins) * pd.Timedelta(f'00:{abs(mins)}:00') return e_time.strftime('%H:%M') class Intervals(object): def __init__(self, ticker): """ Args: ticker: ticker """ self.logger = logs.get_logger(Intervals) self.ticker = ticker self.exch = const.market_info(ticker=self.ticker).get('exch', None) self.active_ss = dict() if self.exch is None: self.logger.error(f'cannot find exch info for {ticker} ...') self.mkt_ss = None else: self.mkt_ss = self.exch.hours for fld in getattr(self.mkt_ss, '_fields'): if fld not in ValidSessions: continue ss = getattr(self.mkt_ss, fld) if ss == SessNA: continue self.active_ss[fld] = ss def market_open(self, session, mins): """ 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.active_ss: return SessNA ss = getattr(self.mkt_ss, session) return Session(ss.start_time, shift_time(ss.start_time, int(mins))) def market_close(self, session, mins): """ 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.active_ss: return SessNA ss = self.active_ss[session] return Session(shift_time(ss.end_time, -int(mins) + 1), ss.end_time) def market_normal(self, session, after_open, before_close): """ 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_time and end_time """ logger = logs.get_logger(self.market_normal) if session not in self.active_ss: return SessNA ss = self.active_ss[session] s_time = shift_time(ss.start_time, int(after_open) + 1) e_time = shift_time(ss.end_time, -int(before_close)) if pd.Timestamp(s_time) >= pd.Timestamp(e_time): logger.warning(f'end time {e_time} is earlier than {s_time} ...') return SessNA return Session(s_time, e_time) def market_exact(self, session, start_time, end_time): """ 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 Returns: Session of start_time and end_time """ if session not in self.active_ss: return SessNA ss = self.active_ss[session] same_day = ss.start_time < ss.end_time if start_time == '': s_time = ss.start_time else: s_time = f'{start_time[:2]}:{start_time[-2:]}' if same_day: s_time = max(s_time, ss.start_time) if end_time == '': e_time = ss.end_time else: e_time = f'{end_time[:2]}:{end_time[-2:]}' if same_day: e_time = min(e_time, ss.end_time) if same_day and (s_time > e_time): return SessNA return Session(start_time=s_time, end_time=e_time) if __name__ == '__main__': """ CommandLine: python -m xbbg.intervals all """ import xdoctest xdoctest.doctest_module(__file__) PKA{vM?r"?"?xbbg/timezone.pyimport pandas as pd import time import pytz from xone import logs DEFAULT_TZ = pytz.FixedOffset(-time.timezone / 60) def get_tz(tz): """ 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_tz('BHP AU Equity') 'Australia/Sydney' """ from xbbg.const import market_info if tz is None: return DEFAULT_TZ to_tz = tz if isinstance(tz, str): if hasattr(TimeZone, tz): to_tz = getattr(TimeZone, tz) else: to_tk = market_info(ticker=tz) if 'exch' in to_tk: to_tz = to_tk['exch'].tz return to_tz def tz_convert(dt, to_tz, from_tz=None): """ 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') >>> tz_convert(dt_1, to_tz='NY') '2018-09-10 04:00:00-04:00' >>> dt_2 = pd.Timestamp('2018-01-10 16:00') >>> tz_convert(dt_2, to_tz='HK', from_tz='NY') '2018-01-11 05:00:00+08:00' >>> dt_3 = '2018-09-10 15:00' >>> tz_convert(dt_3, to_tz='NY', from_tz='JP') '2018-09-10 02:00:00-04:00' """ logger = logs.get_logger(tz_convert, level='info') f_tz, t_tz = get_tz(from_tz), get_tz(to_tz) from_dt = pd.Timestamp(str(dt), tz=f_tz) logger.debug(f'converting {str(from_dt)} from {f_tz} to {t_tz} ...') return str(pd.Timestamp(str(from_dt), tz=t_tz)) class TimeZone(dict): """ Python timezones """ __getattr__ = dict.__getitem__ NY = 'America/New_York' AU = 'Australia/Sydney' JP = 'Asia/Tokyo' SK = 'Asia/Seoul' HK = 'Asia/Hong_Kong' SH = 'Asia/Shanghai' TW = 'Asia/Taipei' SG = 'Asia/Singapore' IN = 'Asia/Calcutta' DB = 'Asia/Dubai' UK = 'Europe/London' ALL_TIMEZONES = [ 'Africa/Abidjan', 'Africa/Accra', 'Africa/Addis_Ababa', 'Africa/Algiers', 'Africa/Asmara', 'Africa/Asmera', 'Africa/Bamako', 'Africa/Bangui', 'Africa/Banjul', 'Africa/Bissau', 'Africa/Blantyre', 'Africa/Brazzaville', 'Africa/Bujumbura', 'Africa/Cairo', 'Africa/Casablanca', 'Africa/Ceuta', 'Africa/Conakry', 'Africa/Dakar', 'Africa/Dar_es_Salaam', 'Africa/Djibouti', 'Africa/Douala', 'Africa/El_Aaiun', 'Africa/Freetown', 'Africa/Gaborone', 'Africa/Harare', 'Africa/Johannesburg', 'Africa/Juba', 'Africa/Kampala', 'Africa/Khartoum', 'Africa/Kigali', 'Africa/Kinshasa', 'Africa/Lagos', 'Africa/Libreville', 'Africa/Lome', 'Africa/Luanda', 'Africa/Lubumbashi', 'Africa/Lusaka', 'Africa/Malabo', 'Africa/Maputo', 'Africa/Maseru', 'Africa/Mbabane', 'Africa/Mogadishu', 'Africa/Monrovia', 'Africa/Nairobi', 'Africa/Ndjamena', 'Africa/Niamey', 'Africa/Nouakchott', 'Africa/Ouagadougou', 'Africa/Porto-Novo', 'Africa/Sao_Tome', 'Africa/Timbuktu', 'Africa/Tripoli', 'Africa/Tunis', 'Africa/Windhoek', 'America/Adak', 'America/Anchorage', 'America/Anguilla', 'America/Antigua', 'America/Araguaina', 'America/Argentina/Buenos_Aires', 'America/Argentina/Catamarca', 'America/Argentina/ComodRivadavia', 'America/Argentina/Cordoba', 'America/Argentina/Jujuy', 'America/Argentina/La_Rioja', 'America/Argentina/Mendoza', 'America/Argentina/Rio_Gallegos', 'America/Argentina/Salta', 'America/Argentina/San_Juan', 'America/Argentina/San_Luis', 'America/Argentina/Tucuman', 'America/Argentina/Ushuaia', 'America/Aruba', 'America/Asuncion', 'America/Atikokan', 'America/Atka', 'America/Bahia', 'America/Bahia_Banderas', 'America/Barbados', 'America/Belem', 'America/Belize', 'America/Blanc-Sablon', 'America/Boa_Vista', 'America/Bogota', 'America/Boise', 'America/Buenos_Aires', 'America/Cambridge_Bay', 'America/Campo_Grande', 'America/Cancun', 'America/Caracas', 'America/Catamarca', 'America/Cayenne', 'America/Cayman', 'America/Chicago', 'America/Chihuahua', 'America/Coral_Harbour', 'America/Cordoba', 'America/Costa_Rica', 'America/Creston', 'America/Cuiaba', 'America/Curacao', 'America/Danmarkshavn', 'America/Dawson', 'America/Dawson_Creek', 'America/Denver', 'America/Detroit', 'America/Dominica', 'America/Edmonton', 'America/Eirunepe', 'America/El_Salvador', 'America/Ensenada', 'America/Fort_Nelson', 'America/Fort_Wayne', 'America/Fortaleza', 'America/Glace_Bay', 'America/Godthab', 'America/Goose_Bay', 'America/Grand_Turk', 'America/Grenada', 'America/Guadeloupe', 'America/Guatemala', 'America/Guayaquil', 'America/Guyana', 'America/Halifax', 'America/Havana', 'America/Hermosillo', 'America/Indiana/Indianapolis', 'America/Indiana/Knox', 'America/Indiana/Marengo', 'America/Indiana/Petersburg', 'America/Indiana/Tell_City', 'America/Indiana/Vevay', 'America/Indiana/Vincennes', 'America/Indiana/Winamac', 'America/Indianapolis', 'America/Inuvik', 'America/Iqaluit', 'America/Jamaica', 'America/Jujuy', 'America/Juneau', 'America/Kentucky/Louisville', 'America/Kentucky/Monticello', 'America/Knox_IN', 'America/Kralendijk', 'America/La_Paz', 'America/Lima', 'America/Los_Angeles', 'America/Louisville', 'America/Lower_Princes', 'America/Maceio', 'America/Managua', 'America/Manaus', 'America/Marigot', 'America/Martinique', 'America/Matamoros', 'America/Mazatlan', 'America/Mendoza', 'America/Menominee', 'America/Merida', 'America/Metlakatla', 'America/Mexico_City', 'America/Miquelon', 'America/Moncton', 'America/Monterrey', 'America/Montevideo', 'America/Montreal', 'America/Montserrat', 'America/Nassau', 'America/New_York', 'America/Nipigon', 'America/Nome', 'America/Noronha', 'America/North_Dakota/Beulah', 'America/North_Dakota/Center', 'America/North_Dakota/New_Salem', 'America/Ojinaga', 'America/Panama', 'America/Pangnirtung', 'America/Paramaribo', 'America/Phoenix', 'America/Port-au-Prince', 'America/Port_of_Spain', 'America/Porto_Acre', 'America/Porto_Velho', 'America/Puerto_Rico', 'America/Punta_Arenas', 'America/Rainy_River', 'America/Rankin_Inlet', 'America/Recife', 'America/Regina', 'America/Resolute', 'America/Rio_Branco', 'America/Rosario', 'America/Santa_Isabel', 'America/Santarem', 'America/Santiago', 'America/Santo_Domingo', 'America/Sao_Paulo', 'America/Scoresbysund', 'America/Shiprock', 'America/Sitka', 'America/St_Barthelemy', 'America/St_Johns', 'America/St_Kitts', 'America/St_Lucia', 'America/St_Thomas', 'America/St_Vincent', 'America/Swift_Current', 'America/Tegucigalpa', 'America/Thule', 'America/Thunder_Bay', 'America/Tijuana', 'America/Toronto', 'America/Tortola', 'America/Vancouver', 'America/Virgin', 'America/Whitehorse', 'America/Winnipeg', 'America/Yakutat', 'America/Yellowknife', 'Antarctica/Casey', 'Antarctica/Davis', 'Antarctica/DumontDUrville', 'Antarctica/Macquarie', 'Antarctica/Mawson', 'Antarctica/McMurdo', 'Antarctica/Palmer', 'Antarctica/Rothera', 'Antarctica/South_Pole', 'Antarctica/Syowa', 'Antarctica/Troll', 'Antarctica/Vostok', 'Arctic/Longyearbyen', 'Asia/Aden', 'Asia/Almaty', 'Asia/Amman', 'Asia/Anadyr', 'Asia/Aqtau', 'Asia/Aqtobe', 'Asia/Ashgabat', 'Asia/Ashkhabad', 'Asia/Atyrau', 'Asia/Baghdad', 'Asia/Bahrain', 'Asia/Baku', 'Asia/Bangkok', 'Asia/Barnaul', 'Asia/Beirut', 'Asia/Bishkek', 'Asia/Brunei', 'Asia/Calcutta', 'Asia/Chita', 'Asia/Choibalsan', 'Asia/Chongqing', 'Asia/Chungking', 'Asia/Colombo', 'Asia/Dacca', 'Asia/Damascus', 'Asia/Dhaka', 'Asia/Dili', 'Asia/Dubai', 'Asia/Dushanbe', 'Asia/Famagusta', 'Asia/Gaza', 'Asia/Harbin', 'Asia/Hebron', 'Asia/Ho_Chi_Minh', 'Asia/Hong_Kong', 'Asia/Hovd', 'Asia/Irkutsk', 'Asia/Istanbul', 'Asia/Jakarta', 'Asia/Jayapura', 'Asia/Jerusalem', 'Asia/Kabul', 'Asia/Kamchatka', 'Asia/Karachi', 'Asia/Kashgar', 'Asia/Kathmandu', 'Asia/Katmandu', 'Asia/Khandyga', 'Asia/Kolkata', 'Asia/Krasnoyarsk', 'Asia/Kuala_Lumpur', 'Asia/Kuching', 'Asia/Kuwait', 'Asia/Macao', 'Asia/Macau', 'Asia/Magadan', 'Asia/Makassar', 'Asia/Manila', 'Asia/Muscat', 'Asia/Nicosia', 'Asia/Novokuznetsk', 'Asia/Novosibirsk', 'Asia/Omsk', 'Asia/Oral', 'Asia/Phnom_Penh', 'Asia/Pontianak', 'Asia/Pyongyang', 'Asia/Qatar', 'Asia/Qyzylorda', 'Asia/Rangoon', 'Asia/Riyadh', 'Asia/Saigon', 'Asia/Sakhalin', 'Asia/Samarkand', 'Asia/Seoul', 'Asia/Shanghai', 'Asia/Singapore', 'Asia/Srednekolymsk', 'Asia/Taipei', 'Asia/Tashkent', 'Asia/Tbilisi', 'Asia/Tehran', 'Asia/Tel_Aviv', 'Asia/Thimbu', 'Asia/Thimphu', 'Asia/Tokyo', 'Asia/Tomsk', 'Asia/Ujung_Pandang', 'Asia/Ulaanbaatar', 'Asia/Ulan_Bator', 'Asia/Urumqi', 'Asia/Ust-Nera', 'Asia/Vientiane', 'Asia/Vladivostok', 'Asia/Yakutsk', 'Asia/Yangon', 'Asia/Yekaterinburg', 'Asia/Yerevan', 'Atlantic/Azores', 'Atlantic/Bermuda', 'Atlantic/Canary', 'Atlantic/Cape_Verde', 'Atlantic/Faeroe', 'Atlantic/Faroe', 'Atlantic/Jan_Mayen', 'Atlantic/Madeira', 'Atlantic/Reykjavik', 'Atlantic/South_Georgia', 'Atlantic/St_Helena', 'Atlantic/Stanley', 'Australia/ACT', 'Australia/Adelaide', 'Australia/Brisbane', 'Australia/Broken_Hill', 'Australia/Canberra', 'Australia/Currie', 'Australia/Darwin', 'Australia/Eucla', 'Australia/Hobart', 'Australia/LHI', 'Australia/Lindeman', 'Australia/Lord_Howe', 'Australia/Melbourne', 'Australia/NSW', 'Australia/North', 'Australia/Perth', 'Australia/Queensland', 'Australia/South', 'Australia/Sydney', 'Australia/Tasmania', 'Australia/Victoria', 'Australia/West', 'Australia/Yancowinna', 'Brazil/Acre', 'Brazil/DeNoronha', 'Brazil/East', 'Brazil/West', 'CET', 'CST6CDT', 'Canada/Atlantic', 'Canada/Central', 'Canada/Eastern', 'Canada/Mountain', 'Canada/Newfoundland', 'Canada/Pacific', 'Canada/Saskatchewan', 'Canada/Yukon', 'Chile/Continental', 'Chile/EasterIsland', 'Cuba', 'EET', 'EST', 'EST5EDT', 'Egypt', 'Eire', 'Etc/GMT', 'Etc/GMT+0', 'Etc/GMT+1', 'Etc/GMT+10', 'Etc/GMT+11', 'Etc/GMT+12', 'Etc/GMT+2', 'Etc/GMT+3', 'Etc/GMT+4', 'Etc/GMT+5', 'Etc/GMT+6', 'Etc/GMT+7', 'Etc/GMT+8', 'Etc/GMT+9', 'Etc/GMT-0', 'Etc/GMT-1', 'Etc/GMT-10', 'Etc/GMT-11', 'Etc/GMT-12', 'Etc/GMT-13', 'Etc/GMT-14', 'Etc/GMT-2', 'Etc/GMT-3', 'Etc/GMT-4', 'Etc/GMT-5', 'Etc/GMT-6', 'Etc/GMT-7', 'Etc/GMT-8', 'Etc/GMT-9', 'Etc/GMT0', 'Etc/Greenwich', 'Etc/UCT', 'Etc/UTC', 'Etc/Universal', 'Etc/Zulu', 'Europe/Amsterdam', 'Europe/Andorra', 'Europe/Astrakhan', 'Europe/Athens', 'Europe/Belfast', 'Europe/Belgrade', 'Europe/Berlin', 'Europe/Bratislava', 'Europe/Brussels', 'Europe/Bucharest', 'Europe/Budapest', 'Europe/Busingen', 'Europe/Chisinau', 'Europe/Copenhagen', 'Europe/Dublin', 'Europe/Gibraltar', 'Europe/Guernsey', 'Europe/Helsinki', 'Europe/Isle_of_Man', 'Europe/Istanbul', 'Europe/Jersey', 'Europe/Kaliningrad', 'Europe/Kiev', 'Europe/Kirov', 'Europe/Lisbon', 'Europe/Ljubljana', 'Europe/London', 'Europe/Luxembourg', 'Europe/Madrid', 'Europe/Malta', 'Europe/Mariehamn', 'Europe/Minsk', 'Europe/Monaco', 'Europe/Moscow', 'Europe/Nicosia', 'Europe/Oslo', 'Europe/Paris', 'Europe/Podgorica', 'Europe/Prague', 'Europe/Riga', 'Europe/Rome', 'Europe/Samara', 'Europe/San_Marino', 'Europe/Sarajevo', 'Europe/Saratov', 'Europe/Simferopol', 'Europe/Skopje', 'Europe/Sofia', 'Europe/Stockholm', 'Europe/Tallinn', 'Europe/Tirane', 'Europe/Tiraspol', 'Europe/Ulyanovsk', 'Europe/Uzhgorod', 'Europe/Vaduz', 'Europe/Vatican', 'Europe/Vienna', 'Europe/Vilnius', 'Europe/Volgograd', 'Europe/Warsaw', 'Europe/Zagreb', 'Europe/Zaporozhye', 'Europe/Zurich', 'GB', 'GB-Eire', 'GMT', 'GMT+0', 'GMT-0', 'GMT0', 'Greenwich', 'HST', 'Hongkong', 'Iceland', 'Indian/Antananarivo', 'Indian/Chagos', 'Indian/Christmas', 'Indian/Cocos', 'Indian/Comoro', 'Indian/Kerguelen', 'Indian/Mahe', 'Indian/Maldives', 'Indian/Mauritius', 'Indian/Mayotte', 'Indian/Reunion', 'Iran', 'Israel', 'Jamaica', 'Japan', 'Kwajalein', 'Libya', 'MET', 'MST', 'MST7MDT', 'Mexico/BajaNorte', 'Mexico/BajaSur', 'Mexico/General', 'NZ', 'NZ-CHAT', 'Navajo', 'PRC', 'PST8PDT', 'Pacific/Apia', 'Pacific/Auckland', 'Pacific/Bougainville', 'Pacific/Chatham', 'Pacific/Chuuk', 'Pacific/Easter', 'Pacific/Efate', 'Pacific/Enderbury', 'Pacific/Fakaofo', 'Pacific/Fiji', 'Pacific/Funafuti', 'Pacific/Galapagos', 'Pacific/Gambier', 'Pacific/Guadalcanal', 'Pacific/Guam', 'Pacific/Honolulu', 'Pacific/Johnston', 'Pacific/Kiritimati', 'Pacific/Kosrae', 'Pacific/Kwajalein', 'Pacific/Majuro', 'Pacific/Marquesas', 'Pacific/Midway', 'Pacific/Nauru', 'Pacific/Niue', 'Pacific/Norfolk', 'Pacific/Noumea', 'Pacific/Pago_Pago', 'Pacific/Palau', 'Pacific/Pitcairn', 'Pacific/Pohnpei', 'Pacific/Ponape', 'Pacific/Port_Moresby', 'Pacific/Rarotonga', 'Pacific/Saipan', 'Pacific/Samoa', 'Pacific/Tahiti', 'Pacific/Tarawa', 'Pacific/Tongatapu', 'Pacific/Truk', 'Pacific/Wake', 'Pacific/Wallis', 'Pacific/Yap', 'Poland', 'Portugal', 'ROC', 'ROK', 'Singapore', 'Turkey', 'UCT', 'US/Alaska', 'US/Aleutian', 'US/Arizona', 'US/Central', 'US/East-Indiana', 'US/Eastern', 'US/Hawaii', 'US/Indiana-Starke', 'US/Michigan', 'US/Mountain', 'US/Pacific', 'US/Samoa', 'UTC', 'Universal', 'W-SU', 'WET', 'Zulu', ] if __name__ == '__main__': """ CommandLine: python -m xbbg.timezone all """ import xdoctest xdoctest.doctest_module(__file__) PKHuM֐xbbg/asset/comdty.pyfrom xbbg.exchange import ExchHours Comdty = [ dict( tickers=['CL'], exch=ExchHours.NYME, freq='M', is_fut=True, ), dict( tickers=['CO', 'XW'], exch=ExchHours.FuturesEuropeICE, freq='M', is_fut=True, ), dict( tickers=['IOE'], exch=ExchHours.CommoditiesDalian, freq='M', is_fut=True, key_month=['J', 'K', 'U'], ), dict( tickers=['RBT'], exch=ExchHours.CommoditiesDalian, freq='M', is_fut=True, key_month=['J', 'K', 'U'], ), dict( tickers=['HG'], exch=ExchHours.CMX, freq='Q', is_fut=True, ), ] PKn+M- xbbg/asset/corp.pyCorp = [ ] PK8YtM,]00xbbg/asset/curncy.pyfrom xbbg.exchange import ExchHours Curncy = [ dict( tickers=[ 'JPY', 'AUD', 'HKD', 'CNHHKD', 'CNH', 'EUR', 'GBP', 'GBPAUD', 'GBPEUR', 'AUDGBP', 'GBPHKD', 'KWN', 'IRN', 'NTN', 'CNH1M', 'ZAR', ], exch=ExchHours.CurrencyGeneric, ), dict( tickers=['KRW'], exch=ExchHours.CurrencySouthKorea, ), dict( tickers=['TWD'], exch=ExchHours.CurrencyTaiwan, ), dict( tickers=['CNYHKD', 'CNY'], exch=ExchHours.CurrencyChina, ), dict( tickers=['INR'], exch=ExchHours.CurrencyIndia, ), dict( tickers=['IRD'], exch=ExchHours.CurrencyDubai, freq='M', is_fut=True, ), dict( tickers=['XID'], exch=ExchHours.CurrencySingapore, freq='M', is_fut=True, ), dict( tickers=['INT'], exch=ExchHours.CurrencyIndia, freq='M', is_fut=True, ), dict( tickers=['DXY'], exch=ExchHours.CurrencyICE, ), ] PK8YtM ѐllxbbg/asset/equity.pyfrom xbbg.exchange import ExchHours Equity = [ dict( exch_codes=['AU'], exch=ExchHours.EquityAustralia, ), dict( exch_codes=['JT', 'JP'], exch=ExchHours.EquityJapan, ), dict( exch_codes=['KS'], exch=ExchHours.EquitySouthKorea, ), dict( exch_codes=['TT'], exch=ExchHours.EquityTaiwan, ), dict( exch_codes=['HK'], exch=ExchHours.EquityHongKong, ), dict( exch_codes=['CH', 'CG', 'CS'], exch=ExchHours.EquityChina, ), dict( exch_codes=['IN', 'IS', 'IB'], exch=ExchHours.EquityIndia, ), dict( exch_codes=['LI', 'LN', 'FP'], exch=ExchHours.EquityLondon, ), dict( exch_codes=['NA'], exch=ExchHours.EquityAmsterdam, ), dict( exch_codes=['ID', 'GR'], exch=ExchHours.EquityDublin, ), dict( exch_codes=['SQ', 'SM'], exch=ExchHours.EquitySpain, ), dict( exch_codes=['US'], exch=ExchHours.EquityUS, ), ] PKٞ9Mqxbbg/asset/futures.pyIndex = [ 'ESA', 'DMA', 'NQA', 'Z A', 'UXA', 'NKA', 'TPA', 'XPA', 'TWA', 'HIA', 'HCA', 'HCA', 'NZA', 'MESA', ] Comdty = [ 'CLA', 'COA' ] PK8YtM xbbg/asset/index.pyfrom xbbg.exchange import ExchHours Index = [ dict( tickers=['XP'], exch=ExchHours.FuturesAustralia, freq='Q', is_fut=True, ), dict( tickers=['AS51'], exch=ExchHours.IndexAustralia, ), dict( tickers=['NKY', 'TPX'], exch=ExchHours.EquityJapan, ), dict( tickers=['NK', 'TP'], exch=ExchHours.FuturesJapan, freq='Q', is_fut=True, ), dict( tickers=['KOSPI2', 'KOSPBMET'], exch=ExchHours.IndexSouthKorea, ), dict( tickers=['KM'], exch=ExchHours.FuturesSouthKorea, freq='Q', is_fut=True, ), dict( tickers=['TWSE'], exch=ExchHours.EquityTaiwan, ), dict( tickers=['TW'], exch=ExchHours.FuturesTaiwan, freq='M', is_fut=True, ), dict( tickers=['HSI', 'HSCEI'], exch=ExchHours.EquityHongKong, ), dict( tickers=['HI', 'HC'], exch=ExchHours.FuturesHongKong, freq='M', is_fut=True, ), dict( tickers=['SHSZ300', 'SHCOMP', 'SZCOMP', 'SZ399006', 'SH000905'], exch=ExchHours.EquityChina, ), dict( tickers=[ 'SPX', 'INDU', 'CCMP', 'RTY', 'RAY', 'SOX', 'S5FINL', 'S5INSU', 'S5TRAN', 'S5UTIL', 'S5ENRS', 'VIX', 'S5IOIL', 'S5STEL', 'S5ITEL', 'S5SECO', 'S5INFT', 'SOX', 'EWAIV', 'EWJIV', 'EWYIV', 'EWTIV', 'EWHIV', 'FXIIV', 'INDAIV', 'AIAIV', 'AAXJIV', 'EEMIV', ], exch=ExchHours.IndexUS, ), dict( tickers=['XU'], exch=ExchHours.FuturesSingapore, freq='M', is_fut=True, ), dict( tickers=['TTMT', 'HDFCB', 'WPRO', 'INFO', 'ICICI', 'DRRD', 'VEDL'], exch=ExchHours.EquityFuturesIndia, freq='M', is_fut=True, ), dict( tickers=['NZ'], exch=ExchHours.IndexFuturesIndia, freq='M', is_fut=True, ), dict( tickers=['NIFTY'], exch=ExchHours.IndexFuturesIndia, ), dict( tickers=['ES', 'DM', 'NQ'], exch=ExchHours.CME, freq='Q', is_fut=True, ), dict( tickers=['Z'], exch=ExchHours.FuturesFinancialsICE, freq='Q', is_fut=True, ), dict( tickers=['UX'], exch=ExchHours.FuturesCBOE, freq='M', is_fut=True, has_sprd=True, ), dict( tickers=['UKX', 'SXXE'], exch=ExchHours.IndexLondon, ), dict( tickers=['SX5E', 'SX5P'], exch=ExchHours.IndexEurope1, ), dict( tickers=['BE500'], exch=ExchHours.IndexEurope2, ), dict( tickers=['MSER', 'MSPE'], exch=ExchHours.IndexEurope3, ), dict( tickers=['USGG2YR', 'USGG10YR', 'USYC2Y10', 'USYC1030', 'USGG30YR'], exch=ExchHours.IndexUS, ), dict( tickers=['MES'], exch=ExchHours.FuturesNYFICE, freq='Q', is_fut=True, ), ] PKSZoM:U&-&-xbbg-0.1.1.dist-info/LICENSE Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. PK!Hd BUcxbbg-0.1.1.dist-info/WHEEL HM K-*ϳR03rOK-J,/RH,rzd&Y)r$[)T&UD"PK!H4f xbbg-0.1.1.dist-info/METADATAM;r0 D{de%M2IBcdH8$C9IݷoAGEcQzpY4}MÓc9;Y#qI=Ub2"!香<#]0X]y!nGZR[Tppg;UѺŖONS=;LNG Zî6g:wp4=OrHPK!H=xbbg-0.1.1.dist-info/RECORDuɲH}= T Ӣ( ^6C"8 !@|II٣vnEn. QGR@f9يrW>G"PhO7l׌@\gJ[*<(Fi7 DF@y1%QLyy-]vYZ{pM{xy6KXQa ͼ[OO:2@K.<֧;sޠ-u(}i7zG΂fѢ S\d!j!k2>8zu!I97*`A_5$-'Ea-Z.TzM\2e`guHn 3XR蹢S읖 uIN L^.Žrp'X^`<)z%͐Q~?evM]Q^5aciK%j˒~Cya Q7LC