def bdib(ticker: str, dt, session='allday', typ='TRADE', **kwargs) -> pd.DataFrame: """ Bloomberg intraday bar data Args: ticker: ticker name dt: date to download session: [allday, day, am, pm, pre, post] typ: [TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK] **kwargs: ref: reference ticker or exchange used as supplement if exchange info is not defined for `ticker` batch: whether is batch process to download data log: level of logs Returns: pd.DataFrame """ from xbbg.core import trials logger = logs.get_logger(bdib, **kwargs) ex_info = const.exch_info(ticker=ticker, **kwargs) if ex_info.empty: raise KeyError(f'Cannot find exchange info for {ticker}') ss_rng = process.time_range(dt=dt, ticker=ticker, session=session, tz=ex_info.tz, **kwargs) data_file = storage.bar_file(ticker=ticker, dt=dt, typ=typ) if files.exists(data_file) and kwargs.get( 'cache', True) and (not kwargs.get('reload', False)): res = (pd.read_parquet(data_file).pipe( pipeline.add_ticker, ticker=ticker).loc[ss_rng[0]:ss_rng[1]]) if not res.empty: logger.debug(f'Loading Bloomberg intraday data from: {data_file}') return res if not process.check_current(dt=dt, logger=logger, **kwargs): return pd.DataFrame() cur_dt = pd.Timestamp(dt).strftime('%Y-%m-%d') q_tckr = ticker if ex_info.get('is_fut', False): is_sprd = ex_info.get( 'has_sprd', False) and (len(ticker[:-1]) != ex_info['tickers'][0]) if not is_sprd: q_tckr = fut_ticker(gen_ticker=ticker, dt=dt, freq=ex_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}' trial_kw = dict(ticker=ticker, dt=dt, typ=typ, func='bdib') num_trials = trials.num_trials(**trial_kw) if num_trials >= 2: if kwargs.get('batch', False): return pd.DataFrame() logger.info(f'{num_trials} trials with no data {info_log}') return pd.DataFrame() while conn.bbg_session(**kwargs).tryNextEvent(): pass time_rng = process.time_range(dt=dt, ticker=ticker, session='allday', **kwargs) request = process.create_request( service='//blp/refdata', request='IntradayBarRequest', settings=[ ('security', ticker), ('eventType', typ), ('interval', kwargs.get('interval', 1)), ('startDateTime', time_rng[0]), ('endDateTime', time_rng[1]), ], **kwargs, ) logger.debug(f'Sending request to Bloomberg ...\n{request}') conn.send_request(request=request, **kwargs) res = pd.DataFrame(process.rec_events(func=process.process_bar, **kwargs)) if res.empty or ('time' not in res): logger.warning(f'No data for {info_log} ...') trials.update_trials(cnt=num_trials + 1, **trial_kw) return pd.DataFrame() data = (res.set_index('time').rename_axis(index=None).rename( columns={ 'numEvents': 'num_trds' }).tz_localize('UTC').tz_convert(ex_info.tz).pipe(pipeline.add_ticker, ticker=ticker)) if kwargs.get('cache', True): storage.save_intraday(data=data[ticker], ticker=ticker, dt=dt, typ=typ, **kwargs) return data.loc[ss_rng[0]:ss_rng[1]]
def bdtick(ticker, dt, session='allday', time_range=None, types=None, **kwargs) -> pd.DataFrame: """ Bloomberg tick data Args: ticker: ticker name dt: date to download session: [allday, day, am, pm, pre, post] time_range: tuple of start and end time (must be converted into UTC) if this is given, `dt` and `session` will be ignored types: str or list, one or combinations of [ TRADE, AT_TRADE, BID, ASK, MID_PRICE, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK, ] Returns: pd.DataFrame """ logger = logs.get_logger(bdtick, **kwargs) if types is None: types = ['TRADE'] exch = const.exch_info(ticker=ticker, **kwargs) if exch.empty: raise LookupError(f'Cannot find exchange info for {ticker}') if isinstance(time_range, (tuple, list)) and (len(time_range) == 2): cur_dt = pd.Timestamp(dt).strftime('%Y-%m-%d') time_rng = (pd.DatetimeIndex([ f'{cur_dt} {time_range[0]}', f'{cur_dt} {time_range[1]}', ]).tz_localize(exch.tz).tz_convert( process.DEFAULT_TZ).tz_convert('UTC')) else: time_rng = process.time_range(dt=dt, ticker=ticker, session=session, **kwargs) while conn.bbg_session(**kwargs).tryNextEvent(): pass request = process.create_request( service='//blp/refdata', request='IntradayTickRequest', settings=[ ('security', ticker), ('startDateTime', time_rng[0]), ('endDateTime', time_rng[1]), ('includeConditionCodes', True), ('includeExchangeCodes', True), ('includeNonPlottableEvents', True), ('includeBrokerCodes', True), ('includeRpsCodes', True), ('includeTradeTime', True), ('includeActionCodes', True), ('includeIndicatorCodes', True), ], append={'eventTypes': types}, **kwargs, ) logger.debug(f'Sending request to Bloomberg ...\n{request}') conn.send_request(request=request) res = pd.DataFrame( process.rec_events(func=process.process_bar, typ='t', **kwargs)) if kwargs.get('raw', False): return res if res.empty or ('time' not in res): return pd.DataFrame() return (res.set_index('time').rename_axis( index=None).tz_localize('UTC').tz_convert(exch.tz).pipe( pipeline.add_ticker, ticker=ticker).rename( columns={ 'size': 'volume', 'type': 'typ', 'conditionCodes': 'cond', 'exchangeCode': 'exch', 'tradeTime': 'trd_time', }))
def bdtick(ticker, dt, session='allday', types=None, **kwargs) -> pd.DataFrame: """ Bloomberg tick data Args: ticker: ticker name dt: date to download session: [allday, day, am, pm, pre, post] types: str or list, one or combinations of [ TRADE, AT_TRADE, BID, ASK, MID_PRICE, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK, ] Returns: pd.DataFrame """ logger = logs.get_logger(bdtick, **kwargs) exch = const.exch_info(ticker=ticker, **kwargs) time_rng = process.time_range(dt=dt, ticker=ticker, session=session, tz=exch.tz, **kwargs) service = conn.bbg_service(service='//blp/refdata', **kwargs) request = service.createRequest('IntradayTickRequest') while conn.bbg_session(**kwargs).tryNextEvent(): pass if types is None: types = ['TRADE'] if isinstance(types, str): types = [types] request.set('security', ticker) for typ in types: request.append('eventTypes', typ) request.set('startDateTime', time_rng[0]) request.set('endDateTime', time_rng[1]) request.set('includeConditionCodes', True) request.set('includeExchangeCodes', True) request.set('includeNonPlottableEvents', True) request.set('includeBrokerCodes', True) request.set('includeRpsCodes', True) request.set('includeTradeTime', True) request.set('includeActionCodes', True) request.set('includeIndicatorCodes', True) logger.debug(f'Sending request to Bloomberg ...\n{request}') conn.send_request(request=request) res = pd.DataFrame( process.rec_events(func=process.process_bar, typ='t', **kwargs)) if kwargs.get('raw', False): return res if res.empty or ('time' not in res): return pd.DataFrame() return (res.set_index('time').rename_axis( index=None).tz_localize('UTC').tz_convert(exch.tz).pipe( pipeline.add_ticker, ticker=ticker).rename( columns={ 'size': 'volume', 'type': 'typ', 'conditionCodes': 'cond', 'exchangeCode': 'exch', 'tradeTime': 'trd_time', }))