Skip to main content

Python library providing a Polars DataFrame interface for easy and intuitive access to Bloomberg API.

Project description

Polars Bloomberg Logo

Polars + Bloomberg Open API

Tests License

Polars + Bloomberg Open API is a Python library that facilitates integration of Bloomberg data into Polars DataFrames. Designed for users familiar with Pandas or Excel, it offers minimal-boilerplate functions such as bdp(), bdh(), and bql(). Leverage Polars' high-performance capabilities alongside the Bloomberg API for lightning-fast DataFrame operations and a minimal memory footprint.

Key Benefits:

  • Intuitive "Excel-like" methods: bdp(), bdh(), bql()
  • Outputs data as Polars DataFrames
  • Lightweight design with no dependency on pandas
  • Quickly prototype, test, and scale complex financial analyses.

Prerequisites

  • Bloomberg Access: A valid Bloomberg terminal license.
  • Bloomberg Python API: The blpapi library must be installed. See the Bloomberg API Library for guidance.
  • Python Version: Python 3.8+ recommended.
  • Installation: pip install polars-bloomberg

Quick Start Guide (5 Minutes)

Below is a simple example to get you started. For more comprehensive examples, please see the examples/ directory.

Concept:
BQuery is your main interface. Using a context manager ensures the connection opens and closes cleanly. Within this session, you can use:

  • bq.bdp() for Bloomberg Data Points (single-value fields).
  • bq.bdh() for Historical Data (time series).
  • bq.bql() for complex Bloomberg Query Language requests.

BDP - Bloomberg Data Point

Example: Fetching the Last Price of Apple and Microsoft

from polars_bloomberg import BQuery

with BQuery() as bq:
    df = bq.bdp(['AAPL US Equity', 'MSFT US Equity'], ['PX_LAST'])
shape: (2, 2)
securityPX_LAST
strf64
"AAPL US Equity"242.84
"MSFT US Equity"443.57
More BDP Examples

BDP with different column types

polars-bloomberg correctly infers column type as shown in this example:

with BQuery() as bq:
    df = bq.bdp(["XS2930103580 Corp", "USX60003AC87 Corp"],
                ["SECURITY_DES", "YAS_ZSPREAD", "CRNCY", "NXT_CALL_DT"])
shape: (2, 5)
securitySECURITY_DESYAS_ZSPREADCRNCYNXT_CALL_DT
strstrf64strdate
"XS2930103580 Corp""SEB 6 3/4 PERP"327.309349"USD"2031-11-04
"USX60003AC87 Corp""NDAFH 6.3 PERP"315.539222"USD"2031-09-25

BDP with overrides

User can submit list of tuples with overrides

with BQuery() as bq:
    df = bq.bdp(["IBM US Equity"], ["PX_LAST", "CRNCY_ADJ_PX_LAST"], 
                overrides=[("EQY_FUND_CRNCY", "SEK")])
</style> shape: (1, 3)
securityPX_LASTCRNCY_ADJ_PX_LAST
strf64f64
"IBM US Equity"238.042607.401

BDP with date overrides

Overrides for dates has to be in format YYYYMMDD

with BQuery() as bq:
    df = bq.bdp(["USX60003AC87 Corp"], ["SETTLE_DT"],
                overrides=[("USER_LOCAL_TRADE_DATE", "20241014")])
shape: (1, 2)
securitySETTLE_DT
strdate
"USX60003AC87 Corp"2024-10-15
with BQuery() as bq:
    df = bq.bdp(['USDSEK Curncy', 'SEKCZK Curncy'], 
                ['SETTLE_DT', 'PX_LAST'], 
                overrides=[('REFERENCE_DATE', '20200715')]
               )
shape: (2, 3)
securitySETTLE_DTPX_LAST
strdatef64
"USDSEK Curncy"2020-07-1710.9343
"SEKCZK Curncy"2020-07-172.1718

BDH - Bloomberg Data History

with BQuery() as bq:
    df = bq.bdh(['AAPL US Equity', 'TSLA US Equity'], 
                ['PX_LAST', 'VOLUME'], 
                start_date=date(2019, 1, 1), 
                end_date=date(2019, 1, 10))
shape: (14, 4)
securitydatePX_LASTVOLUME
strdatef64f64
"AAPL US Equity"2019-01-0239.481.48158948e8
"AAPL US Equity"2019-01-0335.5483.6524878e8
"TSLA US Equity"2019-01-0922.56878.1494175e7
"TSLA US Equity"2019-01-1022.9989.084531e7
More BDH Examples

BDH with options - periodicitySelection: Monthly

with BQuery() as bq:
    df = bq.bdh(['AAPL US Equity'], 
                ['PX_LAST'], 
                start_date=date(2019, 1, 1), 
                end_date=date(2019, 3, 29),
                options={"periodicitySelection": "MONTHLY"})
shape: (3, 3)
securitydatePX_LAST
strdatef64
"AAPL US Equity"2019-01-3141.61
"AAPL US Equity"2019-02-2843.288
"AAPL US Equity"2019-03-2947.488

BQL - Bloomberg Query Language

Allows to run complex bql queries and get result in wide polars.DataFramewith correct polars types

with BQuery() as bq:
    df = bq.bql("get(px_last) for(['IBM US Equity', 'OMX Index'])")
┌───────────────┬────────────┬──────────────┬──────────────────┐
│ ID            ┆ px_last    ┆ px_last.DATE ┆ px_last.CURRENCY │
│ ---           ┆ ---        ┆ ---          ┆ ---              │
│ str           ┆ f64        ┆ date         ┆ str              │
╞═══════════════╪════════════╪══════════════╪══════════════════╡
│ IBM US Equity ┆ 231.024994 ┆ 2024-12-10   ┆ USD              │
│ OMX Index     ┆ 2602.806   ┆ 2024-12-10   ┆ SEK              │
└───────────────┴────────────┴──────────────┴──────────────────┘
More BQL Examples

Actual and Forward EPS Estimates

df = bq.bql("""
    let(#eps=is_eps(fa_period_type='A',
                    fa_period_offset=range(-4,2));)
    get(#eps)
    for(['IBM US Equity'])
""")
shape: (7, 6)
ID#eps#eps.REVISION_DATE#eps.AS_OF_DATE#eps.PERIOD_END_DATE#eps.CURRENCY
strf64datedatedatestr
"IBM US Equity"10.632022-02-222024-12-072019-12-31"USD"
"IBM US Equity"6.282023-02-282024-12-072020-12-31"USD"
"IBM US Equity"9.2362024-12-072024-12-072025-12-31"USD"

ZSpread vs Duration on bonds from SRCH

query="""
let(#dur=duration(duration_type=MODIFIED); 
    #zsprd=spread(spread_type=Z);) 
get(name(), #dur, #zsprd) 
for(filter(screenresults(type=SRCH, screen_name='@COCO'), 
           ticker in ['SEB', 'SHBASS']))
"""

with BQuery() as bq:
    df = bq.bql(query)
shape: (6, 6)
┌───────────────┬─────────────────┬──────────┬────────────┬────────────┬─────────────┐
│ ID            ┆ name()          ┆ #dur     ┆ #dur.DATE  ┆ #zsprd     ┆ #zsprd.DATE │
│ ---           ┆ ---             ┆ ---      ┆ ---        ┆ ---        ┆ ---         │
│ str           ┆ str             ┆ f64      ┆ date       ┆ f64        ┆ date        │
╞═══════════════╪═════════════════╪══════════╪════════════╪════════════╪═════════════╡
│ BW924993 Corp ┆ SEB 6 ⅞ PERP    ┆ 2.244382 ┆ 2024-12-10 ┆ 229.930933 ┆ 2024-12-10  │
│ ZO703956 Corp ┆ SHBASS 4 ¾ PERP ┆ 4.958582 ┆ 2024-12-10 ┆ 269.963777 ┆ 2024-12-10  │
│ ZO703315 Corp ┆ SHBASS 4 ⅜ PERP ┆ 1.968658 ┆ 2024-12-10 ┆ 232.839648 ┆ 2024-12-10  │
│ YU819930 Corp ┆ SEB 6 ¾ PERP    ┆ 5.388785 ┆ 2024-12-10 ┆ 324.70196  ┆ 2024-12-10  │
│ ZQ349286 Corp ┆ SEB 5 ⅛ PERP    ┆ 0.409083 ┆ 2024-12-10 ┆ 165.405465 ┆ 2024-12-10  │
│ YV402592 Corp ┆ SEB Float PERP  ┆ 0.22527  ┆ 2024-12-10 ┆ 248.756    ┆ 2024-12-10  │
└───────────────┴─────────────────┴──────────┴────────────┴────────────┴─────────────┘

Average issuer OAS spread per maturity bucket

query = """
let( 
    #bins = bins(maturity_years,
                 [3,9,18,30],
                 ['(1) 0-3','(2) 3-9','(3) 9-18','(4) 18-30','(5) 30+']);
    #average_spread = avg(group(spread(st=oas),#bins));
)
get(#average_spread)
for(filter(bonds('NVDA US Equity', issuedby = 'ENTITY'),
           maturity_years != NA))
"""

with BQuery() as bq:
    df = bq.bql(query)
┌───────────┬─────────────────┬──────────────────────┬──────────────────────┬──────────────────────┐
│ ID        ┆ #average_spread ┆ #average_spread.DATE ┆ #average_spread.ORIG ┆ #average_spread.#BIN │
│ ---       ┆ ---             ┆ ---                  ┆ _IDS                 ┆ S                    │
│ str       ┆ f64             ┆ date                 ┆ ---                  ┆ ---                  │
│           ┆                 ┆                      ┆ str                  ┆ str                  │
╞═══════════╪═════════════════╪══════════════════════╪══════════════════════╪══════════════════════╡
│ (1) 0-3   ┆ 30.638311       ┆ 2024-12-10           ┆ QZ552396 Corp        ┆ (1) 0-3              │
│ (2) 3-9   ┆ 59.772151       ┆ 2024-12-10           ┆ null                 ┆ (2) 3-9              │
│ (3) 9-18  ┆ 106.722341      ┆ 2024-12-10           ┆ BH393780 Corp        ┆ (3) 9-18             │
│ (4) 18-30 ┆ 129.945414      ┆ 2024-12-10           ┆ BH393781 Corp        ┆ (4) 18-30            │
│ (5) 30+   ┆ 151.318634      ┆ 2024-12-10           ┆ BH393782 Corp        ┆ (5) 30+              │
└───────────┴─────────────────┴──────────────────────┴──────────────────────┴──────────────────────┘

Technical Analysis: stocks with 20d EMA > 200d EMA and RSI > 70

with BQuery() as bq:
    df = bq.bql(
        """
        let(#ema20=emavg(period=20); 
            #ema200=emavg(period=200); 
            #rsi=rsi(close=px_last());)
        get(name(), #ema20, #ema200, #rsi)
        for(filter(members('OMX Index'), 
                    and(#ema20 > #ema200, #rsi > 70)))
        with(fill=PREV)
        """
    )
shape: (2, 10)
IDname()#ema20#ema20.DATE#ema20.CURRENCY#ema200#ema200.DATE#ema200.CURRENCY#rsi#rsi.DATE
strstrf64datestrf64datestrf64date
"SKFB SS Equity""SKF AB"210.1850192024-12-08"SEK"204.167562024-12-08"SEK"72.2555682024-12-08
"ABB SS Equity""ABB Ltd"623.4969422024-12-08"SEK"561.9025772024-12-08"SEK"72.1445562024-12-08

Swedish USD AT1 Bonds with Bid Axis

query="""
let(#ax=axes();)
get(ticker, cpn(), nxt_call_dt(), #ax)
for(filter(bondsuniv(ACTIVE), 
    crncy()=='USD' and 
    basel_iii_designation() == 'Additional Tier 1' and 
    country_iso() == 'SE' and 
    is_axed('Bid') == True))
"""
with BQuery() as bq:
    df = bq.bql(query)
shape: (8, 11)
IDtickercpn()cpn().MULTIPLIERcpn().CPN_TYPnxt_call_dt()#ax#ax.ASK_DEPTH#ax.BID_DEPTH#ax.ASK_TOTAL_SIZE#ax.BID_TOTAL_SIZE
strstrf64f64strdatestri64i64f64f64
"YU819930 Corp""SEB"6.751.0"VARIABLE"2031-11-04"Y"115e61.8e6
"ZQ349286 Corp""SEB"5.1251.0"VARIABLE"2025-05-13"Y"396.7e65e7
"ZF859199 Corp""SWEDA"7.751.0"VARIABLE"2030-03-17"Y"125e67e6
"BW924993 Corp""SEB"6.8751.0"VARIABLE"2027-06-30"Y"238.2e61.1e7
"ZL122341 Corp""SWEDA"7.6251.0"VARIABLE"2028-03-17"Y"162.6e62.34e7
"ZO703956 Corp""SHBASS"4.751.0"VARIABLE"2031-03-01"Y"123.2e66e6
"BR069680 Corp""SWEDA"4.01.0"VARIABLE"2029-03-17"Y"null1null3e6
"ZO703315 Corp""SHBASS"4.3751.0"VARIABLE"2027-03-01"Y"133e67.4e6

Bond universe from Equity Ticker

query="""
let(#rank=normalized_payment_rank();
    #oas=spread(st=oas);
    #nxt_call=nxt_call_dt();
    )
get(name(), #rank, #nxt_call, #oas)
for(filter(bonds('GTN US Equity'), series() == '144A'))
"""
with BQuery() as bq:
    df = bq.bql(query)
┌───────────────┬───────────────────┬──────────────────┬────────────┬─────────────┬────────────┐
│ ID            ┆ name()            ┆ #rank            ┆ #nxt_call  ┆ #oas        ┆ #oas.DATE  │
│ ---           ┆ ---               ┆ ---              ┆ ---        ┆ ---         ┆ ---        │
│ str           ┆ str               ┆ str              ┆ date       ┆ f64         ┆ date       │
╞═══════════════╪═══════════════════╪══════════════════╪════════════╪═════════════╪════════════╡
│ YX231113 Corp ┆ GTN 10 ½ 07/15/29 ┆ 1st Lien Secured ┆ 2026-07-15 ┆ 615.798149  ┆ 2024-12-10 │
│ BS116983 Corp ┆ GTN 5 ⅜ 11/15/31  ┆ Sr Unsecured     ┆ 2026-11-15 ┆ 1144.393892 ┆ 2024-12-10 │
│ AV438089 Corp ┆ GTN 7 05/15/27    ┆ Sr Unsecured     ┆ 2024-12-17 ┆ 389.022271  ┆ 2024-12-10 │
│ ZO860846 Corp ┆ GTN 4 ¾ 10/15/30  ┆ Sr Unsecured     ┆ 2025-10-15 ┆ 1184.969597 ┆ 2024-12-10 │
│ LW375188 Corp ┆ GTN 5 ⅞ 07/15/26  ┆ Sr Unsecured     ┆ 2025-01-06 ┆ 185.544312  ┆ 2024-12-10 │
└───────────────┴───────────────────┴──────────────────┴────────────┴─────────────┴────────────┘

Weekly (total) Returns

query="""
let(#rng = range(-3M, 0D);
    #rets = return_series(calc_interval=#rng,per=W);
    )
get(#rets)
for(filter(bonds('GTN US Equity'), series() == '144A'))
"""
with BQuery() as bq:
    df = bq.bql(query)
shape: (20, 3)
┌───────────────┬───────────┬────────────┐
│ ID            ┆ #rets     ┆ #rets.DATE │
│ ---           ┆ ---       ┆ ---        │
│ str           ┆ f64       ┆ date       │
╞═══════════════╪═══════════╪════════════╡
│ YX231113 Corp ┆ null      ┆ 2024-11-19 │
│ YX231113 Corp ┆ 0.005028  ┆ 2024-11-26 │
│ YX231113 Corp ┆ 0.000326  ┆ 2024-12-03 │
│ YX231113 Corp ┆ 0.000414  ┆ 2024-12-10 │
│ BS116983 Corp ┆ null      ┆ 2024-11-19 │
│ …             ┆ …         ┆ …          │
│ ZO860846 Corp ┆ -0.010198 ┆ 2024-12-10 │
│ LW375188 Corp ┆ null      ┆ 2024-11-19 │
│ LW375188 Corp ┆ -0.000997 ┆ 2024-11-26 │
│ LW375188 Corp ┆ 0.001294  ┆ 2024-12-03 │
│ LW375188 Corp ┆ 0.0011    ┆ 2024-12-10 │
└───────────────┴───────────┴────────────┘

API Documentation

Read the API documentation in examples/ directory

More Examples

Explore additional usage examples in the examples/ directory.

Bloomberg Documentation

For documentation on the Bloomberg API, check out the Bloomberg Developer's page.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

polars_bloomberg-0.2.4.tar.gz (25.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

polars_bloomberg-0.2.4-py3-none-any.whl (15.2 kB view details)

Uploaded Python 3

File details

Details for the file polars_bloomberg-0.2.4.tar.gz.

File metadata

  • Download URL: polars_bloomberg-0.2.4.tar.gz
  • Upload date:
  • Size: 25.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.0.1 CPython/3.12.8

File hashes

Hashes for polars_bloomberg-0.2.4.tar.gz
Algorithm Hash digest
SHA256 dbeaa4eec1f7a39224e19ed588127f7c71cb2effb08f2e3e57db06e86653fa7b
MD5 4546570848be8677b96d76bed1a2893e
BLAKE2b-256 520b987668342bd5f8c874c3932f4f9a750505ba4dd968880f4c831cc40b88b6

See more details on using hashes here.

File details

Details for the file polars_bloomberg-0.2.4-py3-none-any.whl.

File metadata

File hashes

Hashes for polars_bloomberg-0.2.4-py3-none-any.whl
Algorithm Hash digest
SHA256 ccbf54a6dda6b11576c3b47b7196cfe0efeb8e5f11941f232b557a922d105492
MD5 3cd4961e503dc2efa5b0ad14941651f9
BLAKE2b-256 a6063df4cacd1274d487ab77f224ad50d28eee5b3c20bbedaec9dbfaf9253b0e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page