Top-level API reference¶
The inventory below is checked against the actual non-underscore names bound on
bbg_fetch. The package does not currently define __all__; consequently,
the two imported module names are part of the observable top-level surface too.
DEFAULT_START_DATE
DEFAULT_TENOR_YEARS
FX_DICT
IMPVOL_FIELDS_DELTA
IMPVOL_FIELDS_MNY_12M
IMPVOL_FIELDS_MNY_30DAY
IMPVOL_FIELDS_MNY_3MTH
IMPVOL_FIELDS_MNY_60DAY
IMPVOL_FIELDS_MNY_6MTH
OPTION_CHAIN_FIELDS
OptionChainResult
OptionPriceSource
VOLS_START_DATE
bdh
bdp
bds
contract_to_instrument
core
disconnect
fetch_active_futures
fetch_balance_data
fetch_bonds_info
fetch_cds_info
fetch_div_yields
fetch_dividend_history
fetch_field_timeseries_per_tickers
fetch_fields_timeseries_per_ticker
fetch_fundamentals
fetch_futures_contract_table
fetch_index_members_weights
fetch_issuer_isins_from_bond_isins
fetch_last_prices
fetch_option_chain
fetch_tickers_from_isins
fetch_vol_surface
fetch_vol_timeseries
instrument_to_active_ticker
option_chain
recover_option_forward
run
Detailed reference¶
The reference is generated from the installed package and includes imported top-level functions, classes, enums, and constants.
- bbg_fetch.fetch_field_timeseries_per_tickers(tickers, field='PX_LAST', CshAdjNormal=True, CshAdjAbnormal=True, CapChg=True, start_date=Timestamp('1959-01-01 00:00:00'), end_date=None, freq=None)¶
Fetch a single Bloomberg field across multiple tickers, returning a wide DataFrame.
Parameters¶
- tickerslist, tuple, or dict
Bloomberg tickers to fetch. If a dict, keys are queried and values become column names in the output (e.g.
{'ES1 Index': 'SPX'}yields a column labelled'SPX').- fieldstr
Bloomberg field name. Default
'PX_LAST'.- CshAdjNormal, CshAdjAbnormal, CapChgbool
Bloomberg adjustment flags for normal cash dividends, special dividends, and stock splits / capital changes. All default to
True; set toFalsefor raw quoted prices (e.g. on futures, rates).- start_date, end_datepd.Timestamp, optional
Inclusive history range.
end_datedefaults to the current timestamp at call time;start_datedefaults toDEFAULT_START_DATE.- freqstr, optional
Resample frequency (any pandas offset alias, e.g.
'B','M'). Forward-fills missing observations after resampling.None(default) leaves the native frequency.
Returns¶
- pd.DataFrame or None
DatetimeIndex, sorted ascending. Columns are the input tickers (or their dict-mapped labels) in the order they were supplied. Returns
Noneif Bloomberg returns a malformed response.
- Parameters:
tickers (List[str] | Tuple[str] | Dict[str, str])
field (str)
CshAdjNormal (bool)
CshAdjAbnormal (bool)
CapChg (bool)
start_date (Timestamp | None)
end_date (Timestamp | None)
freq (str)
- Return type:
DataFrame | None
- bbg_fetch.fetch_fields_timeseries_per_ticker(ticker, fields=('PX_OPEN', 'PX_HIGH', 'PX_LOW', 'PX_LAST'), CshAdjNormal=True, CshAdjAbnormal=True, CapChg=True, start_date=Timestamp('1959-01-01 00:00:00'), end_date=None)¶
Fetch multiple Bloomberg fields for a single ticker.
Parameters¶
- tickerstr
Bloomberg ticker (e.g.
'AAPL US Equity','ES1 Index').- fieldssequence of str
Bloomberg fields. Default: OHLC (
'PX_OPEN', 'PX_HIGH', 'PX_LOW', 'PX_LAST').- CshAdjNormal, CshAdjAbnormal, CapChgbool
Bloomberg adjustment flags for normal dividends, special dividends, and splits / capital changes. All default to
True.- start_date, end_datepd.Timestamp, optional
Inclusive history range.
end_datedefaults to the current timestamp at call time.
Returns¶
- pd.DataFrame or None
DatetimeIndex, sorted ascending. Columns appear in the order requested in
fields. ReturnsNoneon Bloomberg error or if the response cannot be parsed.
- Parameters:
ticker (str)
fields (Sequence[str])
CshAdjNormal (bool)
CshAdjAbnormal (bool)
CapChg (bool)
start_date (Timestamp)
end_date (Timestamp | None)
- Return type:
DataFrame | None
- bbg_fetch.fetch_fundamentals(tickers, fields=('security_name', 'gics_sector_name'))¶
Fetch reference (BDP) fundamentals for multiple tickers and fields.
Parameters¶
- tickerssequence of str or dict
Bloomberg tickers to query. If a dict, keys are queried and values become the row index in the output.
- fieldssequence of str or dict
Bloomberg field names to fetch. If a dict, keys are queried and values become the column names in the output (e.g.
{'security_name': 'Name', 'gics_sector_name': 'Sector'}).
Returns¶
- pd.DataFrame
Index = tickers (or dict-mapped labels) in the input order. Columns = fields (or dict-mapped labels) in the input order.
- Parameters:
tickers (Sequence[str] | Dict[str, str])
fields (Sequence[str] | Dict[str, str])
- Return type:
DataFrame
- bbg_fetch.fetch_active_futures(generic_ticker='ES1 Index', first_gen=1, max_attempts=3)¶
Need to run with GFUT settings: roll = None. Bloomberg often fails to get joint data for two adjacent futures, so we request each generic separately and align the second request’s date range to the first one’s coverage.
Parameters¶
- generic_tickerstr
Bloomberg generic future ticker, e.g. ‘ES1 Index’.
- first_genint
Generic number for the front contract. Front and second contracts returned will be (first_gen, first_gen + 1).
- max_attemptsint
Number of times to retry a failed Bloomberg call before giving up.
Returns¶
- Tuple[pd.Series, pd.Series]
Front and second-month price series. If a contract cannot be retrieved after
max_attemptstries, an empty Series is returned in its slot.
- Parameters:
generic_ticker (str)
first_gen (int)
max_attempts (int)
- Return type:
Tuple[Series, Series]
- bbg_fetch.fetch_futures_contract_table(ticker='ESA Index', flds=('name', 'px_settle', 'px_last', 'px_bid', 'px_ask', 'bid_size', 'ask_size', 'volume', 'volume_avg_5d', 'open_int', 'fut_cont_size', 'contract_value', 'fut_val_pt', 'quoted_crncy', 'fut_days_expire', 'px_settle_last_dt', 'last_tradeable_dt', 'last_update_dt', 'last_update'), add_timestamp=True, add_gen_number=True, add_carry=True, tz='UTC')¶
Fetch a futures contract chain with optional carry, generic-number, and timestamp columns.
Pulls the
FUT_CHAINfor the specified active future, then BDP-fetchesfldsfor every contract in the chain. Filters out contracts that didn’t return data.Parameters¶
- tickerstr
Bloomberg active future ticker (e.g.
'ESA Index','ES1 Index').- fldssequence of str
Bloomberg fields to fetch per contract. Default covers prices, sizes, volumes, expiry metadata, currency, and last-update timestamps.
- add_timestampbool
If
True, combinelast_update_dtandlast_updateinto a single timezone-awareupdatecolumn (assumed CET source, converted totz), drop the source columns, and add atimestampcolumn with the current UTC time. DefaultTrue.- add_gen_numberbool
If
True, add agen_numbercolumn = 1, 2, 3, … along the chain. DefaultTrue.- add_carrybool
If
Trueand the chain has at least two contracts, add anan_carrycolumn with the annualized roll yield between consecutive contracts:an_carry[i] = - (mid[i] - mid[i-1]) / mid[i-1] / (T[i] - T[i-1])
where
mid = 0.5 * (px_bid + px_ask)andT = fut_days_expire / 365.NaNfor the front contract and wherever bid or ask is missing. DefaultTrue.- tzstr, optional
Target timezone for the combined
updatecolumn. Default'UTC'.
Returns¶
- pd.DataFrame
Indexed by contract ticker, plus a
tickercolumn carrying the input active-future ticker. Columns depend onfldsand theadd_*flags. Returns an empty DataFrame (with atickercolumn) ifFUT_CHAINis empty.
- Parameters:
ticker (str)
flds (Sequence[str])
add_timestamp (bool)
add_gen_number (bool)
add_carry (bool)
tz (str | None)
- Return type:
DataFrame
- bbg_fetch.fetch_vol_timeseries(ticker='SPX Index', vol_fields={'1M_CALL_IMP_VOL_10DELTA_DFLT': '1MC10D.0', '1M_CALL_IMP_VOL_25DELTA_DFLT': '1MC25D.0', '1M_CALL_IMP_VOL_40DELTA_DFLT': '1MC40D.0', '1M_CALL_IMP_VOL_50DELTA_DFLT': '1MC50D.0', '1M_PUT_IMP_VOL_10DELTA_DFLT': '1MP10D.0', '1M_PUT_IMP_VOL_25DELTA_DFLT': '1MP25D.0', '1M_PUT_IMP_VOL_40DELTA_DFLT': '1MP40D.0', '1M_PUT_IMP_VOL_50DELTA_DFLT': '1MP50D.0', '2M_CALL_IMP_VOL_10DELTA_DFLT': '2MC10D.0', '2M_CALL_IMP_VOL_25DELTA_DFLT': '2MC25D.0', '2M_CALL_IMP_VOL_40DELTA_DFLT': '2MC40D.0', '2M_CALL_IMP_VOL_50DELTA_DFLT': '2MC50D.0', '2M_PUT_IMP_VOL_10DELTA_DFLT': '2MP10D.0', '2M_PUT_IMP_VOL_25DELTA_DFLT': '2MP25D.0', '2M_PUT_IMP_VOL_40DELTA_DFLT': '2MP40D.0', '2M_PUT_IMP_VOL_50DELTA_DFLT': '2MP50D.0'}, start_date=Timestamp('2005-01-03 00:00:00'), rate_index='usgg3m Index', add_underlying=True, add_forwards=False, tenor_years=None, rename=True, scaler=0.01)¶
Fetch implied vol time series with optional underlying data and forward prices.
Supports three vol_fields input modes:
Single dict: one tenor, e.g. IMPVOL_FIELDS_DELTA
List of dicts: multi-tenor surface, e.g. [IMPVOL_FIELDS_MNY_30DAY, …, IMPVOL_FIELDS_MNY_12M] Each dict is fetched as a separate Bloomberg call (avoids field-count limits).
List of strings: raw Bloomberg field names, no renaming applied.
Parameters¶
- tickerstr
Bloomberg ticker, e.g. ‘SPX Index’, ‘EURUSD Curncy’.
- vol_fieldsdict or list
Implied vol field specification. Dict keys are Bloomberg field names, values are short labels for column renaming.
- start_datepd.Timestamp
Start date for historical data.
- rate_indexstr
Bloomberg ticker for risk-free rate, e.g. ‘usgg3m Index’.
- add_underlyingbool
If True, prepend spot_price, div_yield (trailing 12M), and rf_rate columns.
- add_forwardsbool
If True, compute per-tenor implied forwards and discount factors. Adds columns fwd_{tenor} = S * exp((r - q) * T) and df_{tenor} = exp(-r * T). Requires add_underlying=True.
- tenor_yearsdict, optional
Map of tenor label → year fraction for forward/discount factor computation. Default: {‘30d’: 30/365, ‘60d’: 60/365, ‘3m’: 0.25, ‘6m’: 0.5, ‘12m’: 1.0}
- renamebool
If True, rename vol columns using dict values. Ignored for list-of-strings input.
- scalerfloat, optional
Multiply vol and rate values by this factor. Default 0.01 converts Bloomberg’s percentage values (e.g. 20.5) to decimals (0.205).
Returns¶
- pd.DataFrame
DatetimeIndex. Columns depend on options: - Vol columns: renamed labels (e.g. ‘30d100.0’) or raw Bloomberg field names - If add_underlying: spot_price, div_yield, rf_rate - If add_forwards: fwd_30d, fwd_60d, …, df_30d, df_60d, …
- Parameters:
ticker (str)
vol_fields (Dict | List)
start_date (Timestamp)
rate_index (str)
add_underlying (bool)
add_forwards (bool)
tenor_years (Dict[str, float] | None)
rename (bool)
scaler (float | None)
- Return type:
DataFrame
- bbg_fetch.fetch_vol_surface(ticker='KOSPI2 Index', value_date=None, vol_fields=({'30DAY_IMPVOL_100.0%MNY_DF': '30d100.0', '30DAY_IMPVOL_102.5%MNY_DF': '30d102.5', '30DAY_IMPVOL_105.0%MNY_DF': '30d105.0', '30DAY_IMPVOL_110.0%MNY_DF': '30d110.0', '30DAY_IMPVOL_120%MNY_DF': '30d120.0', '30DAY_IMPVOL_80%MNY_DF': '30d80.0', '30DAY_IMPVOL_90.0%MNY_DF': '30d90.0', '30DAY_IMPVOL_95.0%MNY_DF': '30d95.0', '30DAY_IMPVOL_97.5%MNY_DF': '30d97.5'}, {'60DAY_IMPVOL_100.0%MNY_DF': '60d100.0', '60DAY_IMPVOL_102.5%MNY_DF': '60d102.5', '60DAY_IMPVOL_105.0%MNY_DF': '60d105.0', '60DAY_IMPVOL_110.0%MNY_DF': '60d110.0', '60DAY_IMPVOL_120%MNY_DF': '60d120.0', '60DAY_IMPVOL_80%MNY_DF': '60d80.0', '60DAY_IMPVOL_90.0%MNY_DF': '60d90.0', '60DAY_IMPVOL_95.0%MNY_DF': '60d95.0', '60DAY_IMPVOL_97.5%MNY_DF': '60d97.5'}, {'3MTH_IMPVOL_100.0%MNY_DF': '3m100.0', '3MTH_IMPVOL_102.5%MNY_DF': '3m102.5', '3MTH_IMPVOL_105.0%MNY_DF': '3m105.0', '3MTH_IMPVOL_110.0%MNY_DF': '3m110.0', '3MTH_IMPVOL_120%MNY_DF': '3m120.0', '3MTH_IMPVOL_80%MNY_DF': '3m80.0', '3MTH_IMPVOL_90.0%MNY_DF': '3m90.0', '3MTH_IMPVOL_95.0%MNY_DF': '3m95.0', '3MTH_IMPVOL_97.5%MNY_DF': '3m97.5'}, {'6MTH_IMPVOL_100.0%MNY_DF': '6m100.0', '6MTH_IMPVOL_102.5%MNY_DF': '6m102.5', '6MTH_IMPVOL_105.0%MNY_DF': '6m105.0', '6MTH_IMPVOL_110.0%MNY_DF': '6m110.0', '6MTH_IMPVOL_120%MNY_DF': '6m120.0', '6MTH_IMPVOL_80%MNY_DF': '6m80.0', '6MTH_IMPVOL_90.0%MNY_DF': '6m90.0', '6MTH_IMPVOL_95.0%MNY_DF': '6m95.0', '6MTH_IMPVOL_97.5%MNY_DF': '6m97.5'}, {'12MTH_IMPVOL_100.0%MNY_DF': '12m100.0', '12MTH_IMPVOL_102.5%MNY_DF': '12m102.5', '12MTH_IMPVOL_105.0%MNY_DF': '12m105.0', '12MTH_IMPVOL_110.0%MNY_DF': '12m110.0', '12MTH_IMPVOL_120%MNY_DF': '12m120.0', '12MTH_IMPVOL_80%MNY_DF': '12m80.0', '12MTH_IMPVOL_90.0%MNY_DF': '12m90.0', '12MTH_IMPVOL_95.0%MNY_DF': '12m95.0', '12MTH_IMPVOL_97.5%MNY_DF': '12m97.5'}), scaler=0.01, lookback_days=10)¶
implied vol surface for one date, indexed by tenor with moneyness columns.
Reshapes the moneyness implied-vol fields (
{tenor}_IMPVOL_{mny}%MNY_DF, the same fields fetch_vol_timeseries uses) into the OVDV grid: rows are tenors, columns are moneyness in percent. Each cell is the last available quote on or before value_date, looked back up to lookback_days to skip non-trading days.Parameters¶
- tickerstr
Bloomberg ticker, e.g.
'KOSPI2 Index'.- value_datepd.Timestamp, optional
As-of date.
Noneuses the latest available quote.- vol_fieldssequence of dict
One dict per tenor, each mapping a Bloomberg field to a short label (
'30d97.5'). The default is the five standard BVOL tenors (30d, 60d, 3m, 6m, 12m) at nine moneyness points. Widen the surface by passing further tenor dicts of verified fields.- scalerfloat, optional
Multiply vols by this.
0.01converts Bloomberg percent (69.6) to decimals (0.696);Noneleaves the percent values shown on the terminal.- lookback_daysint
Calendar days looked back from value_date to find the last available quote.
Returns¶
- pd.DataFrame
Index = tenor labels in
vol_fieldsorder; columns = moneyness (percent, ascending); values = implied vol. Empty DataFrame if no data falls in the window.
Raises¶
- ValueError
If a vol label does not encode a tenor and moneyness (
'30d97.5').
- Parameters:
ticker (str)
value_date (Timestamp | None)
vol_fields (Sequence[Dict[str, str]])
scaler (float | None)
lookback_days (int)
- Return type:
DataFrame
- bbg_fetch.fetch_last_prices(tickers={'AUDUSD Curncy': 'AUD', 'CADUSD Curncy': 'CAD', 'CHFUSD Curncy': 'CHF', 'CNYUSD Curncy': 'CNY', 'EURUSD Curncy': 'EUR', 'GBPUSD Curncy': 'GBP', 'HKDUSD Curncy': 'HKD', 'INRUSD Curncy': 'INR', 'JPYUSD Curncy': 'JPY', 'KRWUSD Curncy': 'KRW', 'MXNUSD Curncy': 'MXN', 'NOKUSD Curncy': 'NOK', 'NZDUSD Curncy': 'NZD', 'PLNUSD Curncy': 'PLN', 'SEKUSD Curncy': 'SEK', 'SGDUSD Curncy': 'SGD', 'TRYUSD Curncy': 'TRY', 'TWDUSD Curncy': 'TWD', 'ZARUSD Curncy': 'ZAR'})¶
fetch last prices of instruments in tickers
- Parameters:
tickers (Sequence[str] | Dict[str, str])
- Return type:
Series
- bbg_fetch.fetch_bonds_info(isins=('US03522AAJ97', 'US126650CZ11'), fields=('id_bb', 'name', 'security_des', 'ult_parent_ticker_exchange', 'crncy', 'amt_outstanding', 'px_last', 'yas_bond_yld', 'yas_oas_sprd', 'yas_mod_dur'), END_DATE_OVERRIDE=None)¶
Fetch reference data for bonds identified by ISIN.
ISINs are queried by appending
' corp'(Bloomberg’s bond yellow key); the returned DataFrame is reindexed back to the original ISINs.Parameters¶
- isinssequence of str
Bond ISINs (e.g.
['US03522AAJ97', 'US126650CZ11']).- fieldssequence of str
Bloomberg fields. Default covers identification, currency, outstanding amount, last price, and YAS analytics (yield, OAS spread, modified duration).
- END_DATE_OVERRIDEstr, optional
Bloomberg
END_DATE_OVERRIDEinYYYYMMDDform, for as-of historical pricing.
Returns¶
- pd.DataFrame
Indexed by ISIN (reindexed to match the input order, with
NaNrows for ISINs Bloomberg couldn’t resolve). Includes anisin_corpcolumn preserving the queried"<ISIN> corp"form.
- Parameters:
isins (Sequence[str])
fields (Sequence[str])
END_DATE_OVERRIDE (str | None)
- Return type:
DataFrame
- bbg_fetch.fetch_cds_info(equity_tickers=('ABI BB Equity', 'CVS US Equity'), field='cds_spread_ticker_5y')¶
fetch cds info
- Parameters:
equity_tickers (Sequence[str])
field (str)
- Return type:
DataFrame
- bbg_fetch.fetch_balance_data(tickers=('ABI BB Equity', 'T US Equity', 'JPM US Equity'), fields=('GICS_SECTOR_NAME', 'BB_ISSR_COMP_BSE_ON_RTGS', 'TOT_COMMON_EQY', 'BS_LT_BORROW', 'BS_ST_BORROW', 'EQY_FUND_CRNCY', 'EARN_YLD', 'RETURN_ON_ASSETS_ADJUSTED', 'NET_DEBT_TO_FFCF', 'NET_DEBT_TO_CASHFLOW', 'FREE_CASH_FLOW_MARGIN', 'CFO_TO_SALES', 'NET_DEBT_PCT_OF_TOT_CAPITAL', 'INTEREST_COVERAGE_RATIO', 'BS_LIQUIDITY_COVERAGE_RATIO', 'NET_DEBT_TO_EBITDA', 'T12_FCF_T12_EBITDA'))¶
fundamentals data for tickers in tickers
- Parameters:
tickers (Sequence[str])
fields (Sequence[str])
- Return type:
DataFrame
- bbg_fetch.fetch_tickers_from_isins(isins=('US88160R1014', 'IL0065100930'))¶
=BDP(“US4592001014 ISIN”, “PARSEKYABLE_DES”) => IBM XX Equity where XX depends on your terminal settings, which you can check on CNDF <Go>. get the main exchange composite ticker, or whatever suits your need (in A3): =BDP(A2,”EQY_PRIM_SECURITY_COMP_EXCH”) => US
- Parameters:
isins (Sequence[str])
- Return type:
List[str]
- bbg_fetch.fetch_dividend_history(ticker='TIP US Equity')¶
- df.columns = [‘declared_date’, ‘ex_date’, ‘record_date’, ‘payable_date’,
‘dividend_amount’, ‘dividend_frequency’, ‘dividend_type’]
- Parameters:
ticker (str)
- Return type:
DataFrame
- bbg_fetch.fetch_div_yields(tickers, dividend_types=('Income', 'Distribution'))¶
Per-event dividend amounts, trailing-twelve-month rolling sums, and trailing-12m yields.
Aggregates duplicate
ex_dateevents bydeclared_date(e.g. when a single distribution is split into multiple records) so each economic dividend is counted once. The yield divides the trailing-12m dividend by the dividend-UNADJUSTED price (PX_LASTwith cash adjustment off), so the denominator is the actual traded price that drops on each ex-date – not a total-return price. Dividing by a cash-adjusted price would understate the yield.Parameters¶
- tickerssequence of str or dict
Bloomberg tickers. If a dict, keys are queried and values become the column names in the returned DataFrames.
- dividend_typessequence of str
Filter on the
dividend_typecolumn fromDVD_HIST_ALL. Common values:'Income','Distribution','Return of Capital','Accumulation'. Default('Income', 'Distribution')– excludes return-of-capital and accumulation events typical of ETFs.
Returns¶
- divspd.DataFrame
Per-event dividend amounts. DatetimeIndex on
ex_date; columns are tickers (or dict-mapped labels).- divs_1ypd.DataFrame
365-calendar-day rolling sum of
divs– the trailing-twelve-month dividend amount as of each ex-date.- divs_yieldpd.DataFrame
Trailing-twelve-month yield:
divs_1yforward-filled onto the daily unadjusted-price grid and divided by that price. Decimal (0.03 == 3%). DatetimeIndex on price dates; columns matchdivs.
- Parameters:
tickers (Sequence[str] | Dict[str, str])
dividend_types (Sequence[str])
- Return type:
Tuple[DataFrame, DataFrame, DataFrame]
- bbg_fetch.fetch_index_members_weights(index='SPCPGN Index', field='INDX_MWEIGHT', END_DATE_OVERRIDE=None)¶
Fetch the constituents of a Bloomberg index using a configurable bulk field.
Parameters¶
- indexstr
Bloomberg index ticker (e.g.
'SPCPGN Index','LUACTRUU Index').- fieldstr
Bulk-data field driving how members are returned:
'INDX_MWEIGHT'(default): members with current portfolio weights; not all indices support this.'INDX_MEMBERS': tickers only, no weights — used for indices that lackINDX_MWEIGHT.'INDX_MEMBERS3': tickers with additional metadata.
- END_DATE_OVERRIDEstr, optional
Bloomberg
END_DATE_OVERRIDEinYYYYMMDDform. Use to retrieve historical membership snapshots.
Returns¶
- pd.DataFrame
Indexed by the first column returned by Bloomberg (typically the member ticker or ISIN). Remaining columns depend on
field.
Raises¶
- ValueError
If Bloomberg returns no data for the (index, field) combination.
- Parameters:
index (str)
field (str)
END_DATE_OVERRIDE (str | None)
- Return type:
DataFrame
- bbg_fetch.instrument_to_active_ticker(instrument='ES1 Index', num=1)¶
ES1 Index to ES{num} Index Z1 Index to Z 1 Index
- Parameters:
instrument (str)
num (int)
- Return type:
str
- bbg_fetch.contract_to_instrument(future)¶
ES1 Index to ES Index
- Parameters:
future (str)
- Return type:
str
- bbg_fetch.fetch_issuer_isins_from_bond_isins(bond_isins=('XS3034073836', 'USY0616GAA14', 'XS3023923314', 'XXXX'))¶
Resolve bond ISINs to their issuer’s equity ISIN via two BDP round-trips.
Walks: bond ISIN →
ult_parent_ticker_exchange→ equity ISIN (viaid_isin). Bond ISINs that don’t resolve to a parent equity becomeNaN.Parameters¶
- bond_isinssequence of str
Bond ISINs to resolve.
Returns¶
- pd.Series
Indexed by the input bond ISINs (in input order). Values are the corresponding issuer equity ISIN, or
NaNwhere resolution failed. Series name is'issuer isin'.
Examples¶
>>> fetch_issuer_isins_from_bond_isins( ... ['XS3034073836', 'USY0616GAA14', 'XS3023923314', 'XXXX'] ... ) XS3034073836 <issuer-isin> USY0616GAA14 <issuer-isin> XS3023923314 <issuer-isin> XXXX NaN Name: issuer isin, dtype: object
- Parameters:
bond_isins (Sequence[str])
- Return type:
Series
- bbg_fetch.fetch_option_chain(underlying='KOSPI2 Index', expiry=None, num_strikes_per_side=20, strike_grid=None, put_call=None, fields=('security_des', 'opt_put_call', 'opt_strike_px', 'opt_expire_dt', 'opt_cont_size', 'opt_undl_px', 'px_bid', 'px_ask', 'px_last', 'ivol_bid', 'ivol_ask', 'ivol_mid', 'delta_mid', 'gamma_mid', 'vega_mid', 'theta_mid', 'px_volume', 'open_int'), yellow_key=' Index', spot=None, points=10000, batch_size=100)¶
listed option chain for an underlying, one row per option, trimmed to a chosen set of strikes.
CHAIN_TICKERS enumerates the listed strikes in one bulk request; the strike set is then chosen by parsing the strike from each ticker before the per-option bdp, so the number of bdp hits is bounded by the selection, not the full chain. Strikes are selected one of two ways:
strike_grid keep the listed strike nearest each target value (both legs) num_strikes_per_side keep a window of listed strikes each side of the ATM strike
strike_grid takes precedence when both are given, and needs no spot. The deep in-the-money strikes dropped by either mode carry only a stale px_last.
Parameters¶
- underlyingstr
Bloomberg underlying ticker, e.g. ‘KOSPI2 Index’.
- expirystr, optional
CHAIN_EXP_DT_OVRD value in YYYYMMDD. None returns every listed expiry.
- num_strikes_per_sideint, optional
Listed strikes kept each side of the ATM strike. None with no strike_grid fetches the full chain, which can be hundreds of strikes — mind the data limit.
- strike_gridsequence of float, optional
Explicit target strikes; the listed strike nearest each value is kept, both legs. Takes precedence over num_strikes_per_side and needs no spot.
- put_callstr, optional
CHAIN_PUT_CALL_TYPE_OVRD value: ‘C’, ‘P’, or None for both.
- fieldssequence of str
Bloomberg fields fetched per option. Default is the OMON row set.
- yellow_keystr
Suffix appended to each chain ticker, e.g. ‘ Index’ for an index option.
- spotfloat, optional
Underlying price locating the ATM strike. None fetches PX_LAST on underlying. Ignored when strike_grid is given or num_strikes_per_side is None.
- pointsint
CHAIN_POINTS_OVRD value, an upper bound on strikes per side. The default is deliberately larger than any real chain.
- batch_sizeint
Tickers per bdp request.
Returns¶
- pd.DataFrame
One row per option, indexed by option ticker (with yellow key), columns the normalised fields. Empty DataFrame with the field columns if the chain is empty.
Raises¶
- ValueError
If expiry is not a valid YYYYMMDD date, num_strikes_per_side or points is not positive, strike_grid is empty, or a chain ticker carries no parseable strike.
- Parameters:
underlying (str)
expiry (str | None)
num_strikes_per_side (int | None)
strike_grid (Sequence[float] | None)
put_call (str | None)
fields (Sequence[str])
yellow_key (str)
spot (float | None)
points (int)
batch_size (int)
- Return type:
DataFrame
- bbg_fetch.recover_option_forward(option_chain, spot, year_fraction, price_source=OptionPriceSource.LAST, num_strikes=20)¶
implied forward and rate from put-call parity by OLS on the call-put price spread.
C(K) - P(K) = exp(-r T) (F - K)
Regressing the spread on strike gives slope = -exp(-r T) and intercept = exp(-r T) F, hence F = -intercept / slope and r = -ln(-slope) / T.
The forward is well determined; the rate is not. Over a short maturity the slope pins F to a fraction of a point, but the discount factor -exp(-r T) is ~ -1 and a 1e-3 error in the slope moves r by order 1%, so r (and any dividend backed out of it as q = r - ln(F / S) / T) is only indicative. r2 near 1 is no comfort: it measures line straightness, not that the slope sits at -1. Prefer a money-market curve for the rate when precision matters.
Parameters¶
- option_chainpd.DataFrame
Output of fetch_option_chain: one row per option with opt_strike_px, opt_put_call, and the price columns required by price_source.
- spotfloat
Underlying price S, used to select the strikes nearest the money.
- year_fractionfloat
Year fraction T to expiry.
- price_sourceOptionPriceSource
MID uses 0.5 * (px_bid + px_ask); LAST uses px_last. LAST spans the full strike grid; MID drops strikes quoted one-sided.
- num_strikesint
Strikes nearest spot, quoted on both legs, used in the regression.
Returns¶
- Dict[str, float]
forward, rate, r2, num_strikes_used.
Raises¶
- ValueError
If year_fraction is not positive, fewer than three strikes are quoted on both legs, or the fitted parity slope is non-negative.
- Parameters:
option_chain (DataFrame)
spot (float)
year_fraction (float)
price_source (OptionPriceSource)
num_strikes (int)
- Return type:
Dict[str, float]
- bbg_fetch.run(underlying='KOSPI2 Index', expiry='20260910', num_strikes_per_side=20, strike_grid=None, price_source=OptionPriceSource.LAST)¶
fetch an option chain and recover the implied forward and rate, in one call.
Choose strikes by num_strikes_per_side (ATM window) or strike_grid (explicit); when both are given strike_grid wins. Spot and the year fraction are inferred from the returned chain: spot = opt_undl_px, year_fraction = (opt_expire_dt - today) / 365 (actual/365). A single expiry is required, since parity mixes expiries otherwise.
Parameters¶
- underlyingstr
Bloomberg underlying ticker, e.g. ‘KOSPI2 Index’.
- expirystr, optional
CHAIN_EXP_DT_OVRD value in YYYYMMDD. Must resolve to a single listed expiry.
- num_strikes_per_sideint, optional
Listed strikes kept each side of the ATM strike. None with no strike_grid fetches the full chain.
- strike_gridsequence of float, optional
Explicit target strikes; the listed strike nearest each value is kept.
- price_sourceOptionPriceSource
Quote driving the parity recovery. LAST spans the full strike grid.
Returns¶
- OptionChainResult
chain, spot, year_fraction, forward, rate, r2, num_strikes_used.
Raises¶
- ValueError
If the chain is empty or does not resolve to a single expiry.
- Parameters:
underlying (str)
expiry (str | None)
num_strikes_per_side (int | None)
strike_grid (Sequence[float] | None)
price_source (OptionPriceSource)
- Return type:
- class bbg_fetch.OptionPriceSource(*values)¶
Bases:
str,Enumwhich quote drives put-call parity.
- class bbg_fetch.OptionChainResult(chain, spot, year_fraction, forward, rate, r2, num_strikes_used)¶
Bases:
objectimmutable snapshot: the option chain with the parity forward and rate.
spot and year_fraction are read from the chain (opt_undl_px and opt_expire_dt); rate is the parity rate and is only indicative at short maturity (see recover_option_forward).
- Parameters:
chain (DataFrame)
spot (float)
year_fraction (float)
forward (float)
rate (float)
r2 (float)
num_strikes_used (int)
- to_csv(path)¶
write the snapshot to one self-contained CSV: the scalars as commented header lines, then the chain. Read back with OptionChainResult.read_csv. Pandas only.
- Parameters:
path (str)
- Return type:
None
- classmethod read_csv(path)¶
read back a snapshot written by to_csv.
The commented header carries the scalars; the chain follows. opt_expire_dt is re-parsed to datetime, which CSV stores as text.
- Parameters:
path (str)
- Return type:
- bbg_fetch.bdp(tickers, flds, **overrides)¶
Point-in-time reference data — equivalent to BDP in Excel.
Returns¶
- pd.DataFrame
Index = tickers, columns = normalized field names.
- Parameters:
tickers (str | Sequence[str])
flds (str | Sequence[str])
overrides (Any)
- Return type:
DataFrame
- bbg_fetch.bdh(tickers, flds, start_date=None, end_date=None, CshAdjNormal=False, CshAdjAbnormal=False, CapChg=False, **overrides)¶
Historical end-of-day data — equivalent to BDH in Excel.
Returns¶
- pd.DataFrame
DatetimeIndex, MultiIndex columns = (ticker, field).
- Parameters:
tickers (str | Sequence[str])
flds (str | Sequence[str])
start_date (Any)
end_date (Any)
CshAdjNormal (bool)
CshAdjAbnormal (bool)
CapChg (bool)
overrides (Any)
- Return type:
DataFrame
- bbg_fetch.bds(tickers, flds, **overrides)¶
Bulk reference data — equivalent to BDS in Excel.
Returns¶
- pd.DataFrame
Rows from the bulk data set, with ticker as (repeated) index and normalized sub-element names as columns.
- Parameters:
tickers (str | Sequence[str])
flds (str | Sequence[str])
overrides (Any)
- Return type:
DataFrame
- bbg_fetch.disconnect()¶
Explicitly stop and discard the shared session.
- Return type:
None
Top-level modules¶
bbg_fetch.core and bbg_fetch.option_chain are also bound on the package
when it is imported. Their supported user-facing callables are documented above
through the top-level namespace.
Bloomberg data fetching utilities.
Provides high-level functions for retrieving equity, futures, fixed-income, FX, options, and index data from Bloomberg via blpapi.
- Install blpapi:
pip install –index-url=https://blpapi.bloomberg.com/repository/releases/python/simple blpapi
option chain retrieval and put-call parity recovery.
Fetch a listed option chain for an underlying (fetch_option_chain), recover the implied forward and rate from put-call parity (recover_option_forward), or do both in one call (run). Depends only on the bdp/bds interface, numpy and pandas.