Language Model Programming Using LMQL

Prompting is Programming with LMQL

Disclaimer: The experiments detailed below are conducted independently and are not related to my current employment. They represent personal endeavors undertaken during my free time, primarily over weekends, with the aim of staying informed about the latest technological developments in the field of large language models. Nothing contained within this blog post should be construed as financial advice or an encouragement to engage in investment activities. The insights derived from the large language models (LLMs) are merely restatements of publicly available information sourced from DataGrapple blogs. These blogs primarily focus on describing the current state of the credit default swap (CDS) market and do not endeavor to predict future market movements.

In this blog, I just toy around with a relatively new framework for querying (large) language models: LMQL, a SQL-like for LLMs. It is a first step toward a novel programming paradigm: Language Model Programming (LMP). These ideas are described in the very interesting paper Prompting Is Programming: A Query Language for Large Language Models.

From time to time, Machine Learners revisit the concept of what “programming” is. In 2017, Andrej Karpathy with Software 2.0, essentially replacing standard human-written code by a (inputs, neural network, labeled outputs) training + inference procedure. Approach also summarized by his Tweet “Gradient descent can write code better than you. I’m sorry.” In this paradigm,

“software development” takes the form of curating, growing, massaging and cleaning labeled datasets.

As of now, this paradigm is not universally adopted, and standard human-written code still rules for many applications.

In Prompting Is Programming: A Query Language for Large Language Models (2023), authors propose the “Language Model Programming (LMP)” paradigm, where one can program using a mix of text prompting (natural language) and scripting with basic constraints and control flow.

LMQL follows the standard “SELECT FROM WHERE” query pattern from SQL as illustrated on the example below:

Language Model Programming Using LMQL

In the rest of this post, I will run a couple of LMQL queries to extract some information from market comments which can be found and read on the DataGrapple - Blog.

I used the same source of market comments to experiment with several interesting tools in the past, namely:

  • Snorkel (01/05/2019) - an instance of Software 2.0
  • VADER (04/05/2019) - mostly because ‘May the Fourth’
  • LIME (26/05/2019) - A tool for model-agnostic explanations of Machine Learning models
  • LIME on Snorkel Labeler (04/08/2019) - Explaining the Snorkel Labeler
  • SetFit (11/03/2023) - Fine-tuning pretrained language models with limited labeled data

You may want to check them out!

And now, some code:

import os
from pprint import pprint
import lmql

# Set the environment variable
os.environ['OPENAI_API_KEY'] = "YOUR_KEY"

Using LMQL, let’s try to extract from a given market comment:

1) the company name,

2) a credit outlook for the company for 2024,

3) the main risk factor mentioned,

and return the result as a valid python dictionary.

@lmql.query()
async def credit_outlook(market_comment):
  '''lmql
  # contextualize
  "You are a credit analysis working at a prestigious hedge fund for a very busy portfolio manager."
  "You read the following market comment: {market_comment}, and you prepare a crisp structured summary for the portfolio manager. This summary should contain the company name, the credit outlook, and the main risk factor to monitor going forward."

  # provide the company name
  "The name of the company which is the main focus of this market comment is:[COMPANY_NAME]" where STOPS_AT(COMPANY_NAME, "\n")

  # provide the credit outlook
  "Based on this market comment only, the overall credit outlook for this company in 2024 can be considered to be[CLS], because[ANALYSIS]" where CLS in [" positive", " neutral", " negative"]

  # provide the main risk factor
  "Based on this market comment only, the largest potential risk for the company (summarized in at most 3 words) that investors should pay particular attention to for the coming year (2024) is:[RISK], because[RISK_ANALYSIS]"

  return {
    "company_name": COMPANY_NAME.rstrip('\n').lstrip(' '),
    "credit_outlook": CLS.lstrip(' '),
    "main_risk_factor": RISK.lstrip(' '),
  }
  '''
market_comment = "Named after “nature” in Hebrew, Teva Pharmaceutical Industries Ltd [TEVA] is the largest generics lab and stands in the top 20 of global pharmas. Headquartered in Israel, Teva grew by acquisitions from 2000, and even launched a $40B bid for Mylan [2015]. 2017 was a pivotal year, as it saw Teva sell assets, slash divvy -75%, cut staff -25%, and market cap went from $60B+ [2016] to almost $10B. For CDS, this turning point saw a floor at 150bp. While today we approach this floor again, some analysts have argued that 2023 was another pivotal year. Indeed, during 2023, Teva managed to “resolve” [$4.25B] the opioids case, “resolve” [$225m] price-fixing case, continued to reduce net debt, got a new CEO and presented a new strategic plan for the coming years, and returned to revenue growth [1st revenue growth in 6 years]. At its May 2023 investor day, TEVA had said they expect to get back to IG over next 2-3 years, from current BB-/BB-/Ba2. TEVA just reported Q4 EBITDA $1,660m [est $1,374m] although there were chunky one-off upfront payments of $430m on a collaboration with Sanofi. Including these, TEVA ended the year with a net leverage 3.5x. Late last month [Jan 31], TEVA announced its intention to divest its API [active pharmaceutical ingredients] business TAPI, expected done by H1-25, this could take net leverage close but above 3x. Going forward, TEVA guided for FCF $1.7-2.0B this year [EBITDA $4.5-5.0B]. Bloomberg consensus seems more optimistic, with 2.3B penciled in, for both this year and next. Just like that. Now, TEVA still has a decent $20B+ of debt outstanding, ’24 and ’25 maturities seem within anticipated FCF, but the interesting one may be ’26 [$3.4B bonds maturing that year]."

pprint(market_comment)
('Named after “nature” in Hebrew, Teva Pharmaceutical Industries Ltd [TEVA] is '
 'the largest generics lab and stands in the top 20 of global pharmas. '
 'Headquartered in Israel, Teva grew by acquisitions from 2000, and even '
 'launched a $40B bid for Mylan [2015]. 2017 was a pivotal year, as it saw '
 'Teva sell assets, slash divvy -75%, cut staff -25%, and market cap went from '
 '$60B+ [2016] to almost $10B. For CDS, this turning point saw a floor at '
 '150bp. While today we approach this floor again, some analysts have argued '
 'that 2023 was another pivotal year. Indeed, during 2023, Teva managed to '
 '“resolve” [$4.25B] the opioids case, “resolve” [$225m] price-fixing case, '
 'continued to reduce net debt, got a new CEO and presented a new strategic '
 'plan for the coming years, and returned to revenue growth [1st revenue '
 'growth in 6 years]. At its May 2023 investor day, TEVA had said they expect '
 'to get back to IG over next 2-3 years, from current BB-/BB-/Ba2. TEVA just '
 'reported Q4 EBITDA $1,660m [est $1,374m] although there were chunky one-off '
 'upfront payments of $430m on a collaboration with Sanofi. Including these, '
 'TEVA ended the year with a net leverage 3.5x. Late last month [Jan 31], TEVA '
 'announced its intention to divest its API [active pharmaceutical '
 'ingredients] business TAPI, expected done by H1-25, this could take net '
 'leverage close but above 3x. Going forward, TEVA guided for FCF $1.7-2.0B '
 'this year [EBITDA $4.5-5.0B]. Bloomberg consensus seems more optimistic, '
 'with 2.3B penciled in, for both this year and next. Just like that. Now, '
 'TEVA still has a decent $20B+ of debt outstanding, ’24 and ’25 maturities '
 'seem within anticipated FCF, but the interesting one may be ’26 [$3.4B bonds '
 'maturing that year].')
result = await credit_outlook(market_comment)

pprint(result)
{'company_name': 'Teva Pharmaceutical Industries Ltd [TEVA].',
 'credit_outlook': 'positive',
 'main_risk_factor': 'Divestment, Debt Maturities.'}
market_comment = "As usual, Swedish companies reported ahead of most Europeans. Telefonaktiebolaget LM Ericsson [ERICB - Ba1 / BBB- / BBB-] is the company that has invented Bluetooth technology, they are one of the world’s biggest providers of 5G networking equipment, they own c60k patents. Ericsson CDS is a constituent of XOver since series s27. It was in the Main index before that, since series s16. Last month, Ericsson 5-year CDS widened +6bp on earnings day, which extended a series of 8 consecutive widenings on quarterly earnings day. This move was little however, if compared to the average +16bp move in the previous 7 releases. The market surely got accustomed to these downbeat releases [and to the rallies in between these releases], allowing Ericsson 5-year CDS to remain close to one-year tight, 120bp handle. Ericsson CEO warned that the market [outside of China] will continue to decline in 2024. In 2024, Ericsson expects a continued drop in mobile business but is ready for a turnaround. Q4 revenues fell by -17%, mainly due to a -23% decline in NA Networks. While India still contributed to growth, it slowed down notably. Ericsson predicts a global -4% decline in RAN market, offset by cloud software and services & enterprise. FCF decreased on lower EBIT, restructuring charges, and WC. Ericsson ended 2023 with SEK7.8b net cash, down from SEK23.3b at the end of 2022. 2024 is still young but it sounds like another sluggish year, with subdued spending from mobile service providers who have been slower than anticipated to roll out 5G. Longer term, Ericsson’s duopoly also risks being disrupted by ORAN [open radio access networks - operators can choose antennas/infrastructure vendors]. Despite all that, Ericsson confirmed SEK2.70/sh divvy. On the bright side of things, EBIT margin before restructuring charges has surpassed 10%, enabling management to maintain mid-term margin targets: EBITA [15-18%] FCF [9-12%]. Moreover, progress was made on the SEK12b cost savings plan, with 50% done in 2023. Finally, the $14B AT&T deal is hoped to increase revenues in H2. The latter points talk in favor of Ericsson, relative to its peer Nokia, which trades almost 20bp tighter."

pprint(market_comment)
('As usual, Swedish companies reported ahead of most Europeans. '
 'Telefonaktiebolaget LM Ericsson [ERICB - Ba1 / BBB- / BBB-] is the company '
 'that has invented Bluetooth technology, they are one of the world’s biggest '
 'providers of 5G networking equipment, they own c60k patents. Ericsson CDS is '
 'a constituent of XOver since series s27. It was in the Main index before '
 'that, since series s16. Last month, Ericsson 5-year CDS widened +6bp on '
 'earnings day, which extended a series of 8 consecutive widenings on '
 'quarterly earnings day. This move was little however, if compared to the '
 'average +16bp move in the previous 7 releases. The market surely got '
 'accustomed to these downbeat releases [and to the rallies in between these '
 'releases], allowing Ericsson 5-year CDS to remain close to one-year tight, '
 '120bp handle. Ericsson CEO warned that the market [outside of China] will '
 'continue to decline in 2024. In 2024, Ericsson expects a continued drop in '
 'mobile business but is ready for a turnaround. Q4 revenues fell by -17%, '
 'mainly due to a -23% decline in NA Networks. While India still contributed '
 'to growth, it slowed down notably. Ericsson predicts a global -4% decline in '
 'RAN market, offset by cloud software and services & enterprise. FCF '
 'decreased on lower EBIT, restructuring charges, and WC. Ericsson ended 2023 '
 'with SEK7.8b net cash, down from SEK23.3b at the end of 2022. 2024 is still '
 'young but it sounds like another sluggish year, with subdued spending from '
 'mobile service providers who have been slower than anticipated to roll out '
 '5G. Longer term, Ericsson’s duopoly also risks being disrupted by ORAN [open '
 'radio access networks - operators can choose antennas/infrastructure '
 'vendors]. Despite all that, Ericsson confirmed SEK2.70/sh divvy. On the '
 'bright side of things, EBIT margin before restructuring charges has '
 'surpassed 10%, enabling management to maintain mid-term margin targets: '
 'EBITA [15-18%] FCF [9-12%]. Moreover, progress was made on the SEK12b cost '
 'savings plan, with 50% done in 2023. Finally, the $14B AT&T deal is hoped to '
 'increase revenues in H2. The latter points talk in favor of Ericsson, '
 'relative to its peer Nokia, which trades almost 20bp tighter.')
result = await credit_outlook(market_comment)

pprint(result)
{'company_name': 'Telefonaktiebolaget LM Ericsson.',
 'credit_outlook': 'negative',
 'main_risk_factor': 'ORAN disruption.'}
market_comment = "Intrum is a Sweden-based credit management services company with subsidiaries in Europe. They offer services covering the entire credit management chain, ranging from prospecting and segmenting to payment management services, collection and payment services [sales ledger, reminder, e-commerce, VAT refunds, debt collection, debt surveillance]. Intrum CDS is a constituent of XOver since s28, currently rated B2/BB/BB-. Last summer, Intrum reported available liquidity SEK 13b and SEK 61.3b total debt [bonds CPs PPs RCF] and was planning to cut leverage by scrapping 2024 dividend and exiting 3 additional markets completely [Czech Republic, Slovakia and Hungary]. This week, not only did we learn that the Eastern Europe exit was not guaranteed any longer either, but Intrum also agreed to sell part of its portfolio, to raise SEK8.2b [by H1 end]. This confirms rumours from December, and covers slightly more than a third of debt due by 2025 end. So, Intrum sold two thirds what could be their crown jewel assets. The assets they could sell, anyway. For 98% of Sept 30th book value. Retaining a 35% stake in the entity acquiring them. Cerberus owning the other 65%. And Intrum agreed to keep servicing the portfolio for at least 5 years. Even before the call Tuesday morning, this benefitted the very short end of the curve, but was already slight negative for the longer end and for the equity [FCF dilutive, increasing leverage]. While Tuesday morning started around 13.5% upfront [5-year / before the call], Intrum CDS had reached 18% upfront by noon, and widened a total +8pt over two sessions. Skepticism about achieving servicing targets, reduced RCF capacity, limited asset sales prospects going forward, are likely to keep Intrum CDS in the top 3 of widest names in crossover benchmark. Its now reverted tighter -2.5pt over the past two sessions, in a slight reversal. A successful RCF maturity extension is what could take it back further."

pprint(market_comment)
('Intrum is a Sweden-based credit management services company with '
 'subsidiaries in Europe. They offer services covering the entire credit '
 'management chain, ranging from prospecting and segmenting to payment '
 'management services, collection and payment services [sales ledger, '
 'reminder, e-commerce, VAT refunds, debt collection, debt surveillance]. '
 'Intrum CDS is a constituent of XOver since s28, currently rated B2/BB/BB-. '
 'Last summer, Intrum reported available liquidity SEK 13b and SEK 61.3b total '
 'debt [bonds CPs PPs RCF] and was planning to cut leverage by scrapping 2024 '
 'dividend and exiting 3 additional markets completely [Czech Republic, '
 'Slovakia and Hungary]. This week, not only did we learn that the Eastern '
 'Europe exit was not guaranteed any longer either, but Intrum also agreed to '
 'sell part of its portfolio, to raise SEK8.2b [by H1 end]. This confirms '
 'rumours from December, and covers slightly more than a third of debt due by '
 '2025 end. So, Intrum sold two thirds what could be their crown jewel assets. '
 'The assets they could sell, anyway. For 98% of Sept 30th book value. '
 'Retaining a 35% stake in the entity acquiring them. Cerberus owning the '
 'other 65%. And Intrum agreed to keep servicing the portfolio for at least 5 '
 'years. Even before the call Tuesday morning, this benefitted the very short '
 'end of the curve, but was already slight negative for the longer end and for '
 'the equity [FCF dilutive, increasing leverage]. While Tuesday morning '
 'started around 13.5% upfront [5-year / before the call], Intrum CDS had '
 'reached 18% upfront by noon, and widened a total +8pt over two sessions. '
 'Skepticism about achieving servicing targets, reduced RCF capacity, limited '
 'asset sales prospects going forward, are likely to keep Intrum CDS in the '
 'top 3 of widest names in crossover benchmark. Its now reverted tighter '
 '-2.5pt over the past two sessions, in a slight reversal. A successful RCF '
 'maturity extension is what could take it back further.')
result = await credit_outlook(market_comment)

pprint(result)
{'company_name': 'Intrum',
 'credit_outlook': 'negative',
 'main_risk_factor': 'RCF maturity extension.'}
market_comment = "CMA CGM SA [CMACG] is the #3 global shipping co. The services they provide include vessel/container fleet management, freight delivery, logistics, cargo cruises. CMA CGM is privately controlled by the Saade family [founders]. CMA CGM is HQ’d in Marseille and sponsors the [un]beloved OM football club. CMA CGM CDS has been in CrossOver indices from s25 to s38. After reaching 50% upfront at the peak of the covid financial crisis, CMA CGM CDS tightened massively and continuously, with conservative balance-sheet management coupled with surging earnings in the subsequent 2 years, thanks to high freight rates and saturated supply chains. While CMA CGM had less than €1.7B cash at EoY-20, they reported €11.3B cash at EoY-22. Jan 30 last year, CMA-CGM 5-year CDS spread squeezed tighter -110bp to 285bp, after reports that they’d redeem €525M 7.5% 26s at 103.75. Some analysts at the time noted CMACG CDS might find itself without any deliverable obligation, temporarily orphan. Since then, CMA CGM has not come back to the market, but still guarantees c€100m Fenix Marine debt, c€80m first lien secured loans at SCI Tour d’Arenc, on top of the €200m+ first lien secured loans at CMA CGM SA. Last May, CMA CGM Group granted a put option to the Bolloré Group to sell the transport and logistics operations of Bolloré Logistics. CMA CGM then started reporting significantly lower net income [$2B Q1-23 from $7B+ Q1-22] marking the end of two golden years. And last July, the Bolloré Group announced that it signed the share purchase agreement to sell 100% of Bolloré Logistics to the CMA CGM Group, purchase price €4.65B ex net debt, completion subject to antitrust and foreign investment clearances. In much smaller acquisitions, the Saade family has taken a 10% stake in French broadcaster M6, a stake in online media Brut and bought newspaper La Tribune, regional newspaper La Provence. June last year, Moody’s took CMA CGM's long-term corporate family rating up one notch to Ba1, with a stable outlook [from positive], praising continued high FCF generation used to fund both logistics and terminals acquisitions, as well as debt reduction, strengthening B/S. During H2-23 and to date, the open interest reported at clearing houses on CMA CGM CDS, has been about halved, now just shy of €400m across Ice Clear and LCH, and across all maturities, highlighting the depth of the short cutting enterprise that’s been taking place, although the fact that this name is not in CrossOver indices since series s38 surely played a role. Aside October-last-year macro weakness, there has been NO exit door for shorts on CMA CGM CDS. More recently, the fact that several shipping companies announced a pause on Red Sea passages [following USUK/Houthi local war -- inducing a c30% significant extension via South Africa] is likely to boost container companies’ earnings prospects. On that, Reuters has reported that CMA CGM’s Asia-Med freight rates had soared by up to 100% [!] as of this past Monday, compared to Monday Jan 1st. Absent a short resolution in the Red Sea, 200bp does not feel like a solid floor."

pprint(market_comment)
('CMA CGM SA [CMACG] is the #3 global shipping co. The services they provide '
 'include vessel/container fleet management, freight delivery, logistics, '
 'cargo cruises. CMA CGM is privately controlled by the Saade family '
 '[founders]. CMA CGM is HQ’d in Marseille and sponsors the [un]beloved OM '
 'football club. CMA CGM CDS has been in CrossOver indices from s25 to s38. '
 'After reaching 50% upfront at the peak of the covid financial crisis, CMA '
 'CGM CDS tightened massively and continuously, with conservative '
 'balance-sheet management coupled with surging earnings in the subsequent 2 '
 'years, thanks to high freight rates and saturated supply chains. While CMA '
 'CGM had less than €1.7B cash at EoY-20, they reported €11.3B cash at EoY-22. '
 'Jan 30 last year, CMA-CGM 5-year CDS spread squeezed tighter -110bp to '
 '285bp, after reports that they’d redeem €525M 7.5% 26s at 103.75. Some '
 'analysts at the time noted CMACG CDS might find itself without any '
 'deliverable obligation, temporarily orphan. Since then, CMA CGM has not come '
 'back to the market, but still guarantees c€100m Fenix Marine debt, c€80m '
 'first lien secured loans at SCI Tour d’Arenc, on top of the €200m+ first '
 'lien secured loans at CMA CGM SA. Last May, CMA CGM Group granted a put '
 'option to the Bolloré Group to sell the transport and logistics operations '
 'of Bolloré Logistics. CMA CGM then started reporting significantly lower net '
 'income [$2B Q1-23 from $7B+ Q1-22] marking the end of two golden years. And '
 'last July, the Bolloré Group announced that it signed the share purchase '
 'agreement to sell 100% of Bolloré Logistics to the CMA CGM Group, purchase '
 'price €4.65B ex net debt, completion subject to antitrust and foreign '
 'investment clearances. In much smaller acquisitions, the Saade family has '
 'taken a 10% stake in French broadcaster M6, a stake in online media Brut and '
 'bought newspaper La Tribune, regional newspaper La Provence. June last year, '
 "Moody’s took CMA CGM's long-term corporate family rating up one notch to "
 'Ba1, with a stable outlook [from positive], praising continued high FCF '
 'generation used to fund both logistics and terminals acquisitions, as well '
 'as debt reduction, strengthening B/S. During H2-23 and to date, the open '
 'interest reported at clearing houses on CMA CGM CDS, has been about halved, '
 'now just shy of €400m across Ice Clear and LCH, and across all maturities, '
 'highlighting the depth of the short cutting enterprise that’s been taking '
 'place, although the fact that this name is not in CrossOver indices since '
 'series s38 surely played a role. Aside October-last-year macro weakness, '
 'there has been NO exit door for shorts on CMA CGM CDS. More recently, the '
 'fact that several shipping companies announced a pause on Red Sea passages '
 '[following USUK/Houthi local war -- inducing a c30% significant extension '
 'via South Africa] is likely to boost container companies’ earnings '
 'prospects. On that, Reuters has reported that CMA CGM’s Asia-Med freight '
 'rates had soared by up to 100% [!] as of this past Monday, compared to '
 'Monday Jan 1st. Absent a short resolution in the Red Sea, 200bp does not '
 'feel like a solid floor.')
result = await credit_outlook(market_comment)

pprint(result)
{'company_name': 'CMA CGM SA.',
 'credit_outlook': 'positive',
 'main_risk_factor': 'Red Sea conflict.'}
market_comment = "Founded in 1909 as a small family-run clinical analysis laboratory in Barcelona, Grifols S.A. is now a global pharma/chemical manufacturer, European leader as producer of blood plasma-based products. Grifols also supply devices, instruments, and reagents for clinical testing laboratories. Rated Caa1/B-/B+ Grifols has its CDS in all CrossOver indices since vintage s28 included. COVID had been the primary driver of reduced plasma volumes, and started a new era for Grifols CDS. EBITDA margin remained strong 25% [20] 20% [21] but COVID net impact on EBITDA was -€500m [lower plasma volumes -€420m] and net leverage increased in 2021 off strategic acquisitions [€520m]. Now valued €5.5B in the stock market, Grifols had reported €10B long term debt as of 2022 end. They have two outstanding bonds totaling €2B due 2025, the next major bonds maturity year being 2027 [roughly another €2B]. In June 2022, Grifols outperformed after a weak H1 [300bp -> 600bp] and Grifols stocks fell, as they were reported to be in talks to raise €2B equity. This was seen as showing a shift in Grifols family vision about leverage and control. However this was after leverage reduction had been guided in February 2022. At the time net debt €5.8B [end 2021] net leverage 5.4x, liquidity €1.3B cash €0.7B. Last June 14, Grifols 5-year CDS tightened -70bp to 430bp, as Grifols may sell off assets including the 26% in Shanghai RAAS it bought in 2019. Grifols had entered a strategic alliance with the Chinese group in 2020. Grifols SA said that they would expect to receive $1.5B if a deal goes through, boosting their debt cutting effort. The beautiful rally ended THIS WEEK. On Tuesday [Jan 9] Gotham City Research LLC stated that Grifols manipulates reported debt & EBITDA to artificially reduce reported leverage to 6x, which they believe is closer to 12x. Gotham argued that both Grifols and Scranton Enterprises [a Grifols family vehicle] fully consolidate BPC + Haema onto their financial statements, a deceptive and incorrect treatment. Gotham said that should their estimate of Grifols’ true leverage be correct, the company should face notably higher financing costs, and they believe that Grifols equities are uninvestable, “likely zero”. Gotham said Grifols fully consolidates both Haema and BPC Plasma, despite owning 0% of each company, Haema + BPC are material to Grifols as they account for c40% of Grifols earnings from non-controlling interests, Scranton Enterprises also fully consolidates BPC Plasma and Haema, these entities’ earnings appear to account for >100% of Scranton’s earnings, while Scranton owns 8.4% of Grifols. At a lesser level, Gotham claimed that Grifols lent Scranton $95m in 2018, a loan seeming tied to the BPC/Haema transaction, yet this loan was undisclosed in Grifols’ filings, only appearing in Scranton filings. Scranton’s 2021 filing shows an increase in liabilities of €59m relating to “advance payments from Grifols Worldwide Operations Ltd”, another transaction undisclosed in Grifols filings. Finally, Gotham argued that while Grifols’ CEO is hailed as a change in direction, he has actually been with Grifols since 2006, and was on the board at the time the suspect transactions occurred. Grifols put out a communique commenting upon “recent false information and speculations published by Gotham City Research regarding their accounting and financial disclosure”. In this, Grifols did deny and reject allegations of wrongful accounting or reporting practices of their consolidated financial statements, noting that their annual audits are conducted by one of the big-four audit firms. On Wednesday [Jan 10], the owner of Gotham City Research, General Industrial Partners, reduced its short position in Grifols to 0.06% from 0.6%. Job done. Grifols shares pared their two-day decline to 18%. From 43% early Tuesday. Today [Jan 12], Grifols 5-year CDS widened back roughly 90bp, on concerns about the collapse of a $1.8B deal to sell a stake in Shanghai RAAS Blood Products to a Chinese player named Haier. The market fears a breakdown in the deal due to the turmoil ignited this week by Gotham. However, some other analysts express confidence that the deal w ill be closed in the coming months."

pprint(market_comment)
('Founded in 1909 as a small family-run clinical analysis laboratory in '
 'Barcelona, Grifols S.A. is now a global pharma/chemical manufacturer, '
 'European leader as producer of blood plasma-based products. Grifols also '
 'supply devices, instruments, and reagents for clinical testing laboratories. '
 'Rated Caa1/B-/B+ Grifols has its CDS in all CrossOver indices since vintage '
 's28 included. COVID had been the primary driver of reduced plasma volumes, '
 'and started a new era for Grifols CDS. EBITDA margin remained strong 25% '
 '[20] 20% [21] but COVID net impact on EBITDA was -€500m [lower plasma '
 'volumes -€420m] and net leverage increased in 2021 off strategic '
 'acquisitions [€520m]. Now valued €5.5B in the stock market, Grifols had '
 'reported €10B long term debt as of 2022 end. They have two outstanding bonds '
 'totaling €2B due 2025, the next major bonds maturity year being 2027 '
 '[roughly another €2B]. In June 2022, Grifols outperformed after a weak H1 '
 '[300bp -> 600bp] and Grifols stocks fell, as they were reported to be in '
 'talks to raise €2B equity. This was seen as showing a shift in Grifols '
 'family vision about leverage and control. However this was after leverage '
 'reduction had been guided in February 2022. At the time net debt €5.8B [end '
 '2021] net leverage 5.4x, liquidity €1.3B cash €0.7B. Last June 14, Grifols '
 '5-year CDS tightened -70bp to 430bp, as Grifols may sell off assets '
 'including the 26% in Shanghai RAAS it bought in 2019. Grifols had entered a '
 'strategic alliance with the Chinese group in 2020. Grifols SA said that they '
 'would expect to receive $1.5B if a deal goes through, boosting their debt '
 'cutting effort. The beautiful rally ended THIS WEEK. On Tuesday [Jan 9] '
 'Gotham City Research LLC stated that Grifols manipulates reported debt & '
 'EBITDA to artificially reduce reported leverage to 6x, which they believe is '
 'closer to 12x. Gotham argued that both Grifols and Scranton Enterprises [a '
 'Grifols family vehicle] fully consolidate BPC + Haema onto their financial '
 'statements, a deceptive and incorrect treatment. Gotham said that should '
 'their estimate of Grifols’ true leverage be correct, the company should face '
 'notably higher financing costs, and they believe that Grifols equities are '
 'uninvestable, “likely zero”. Gotham said Grifols fully consolidates both '
 'Haema and BPC Plasma, despite owning 0% of each company, Haema + BPC are '
 'material to Grifols as they account for c40% of Grifols earnings from '
 'non-controlling interests, Scranton Enterprises also fully consolidates BPC '
 'Plasma and Haema, these entities’ earnings appear to account for >100% of '
 'Scranton’s earnings, while Scranton owns 8.4% of Grifols. At a lesser level, '
 'Gotham claimed that Grifols lent Scranton $95m in 2018, a loan seeming tied '
 'to the BPC/Haema transaction, yet this loan was undisclosed in Grifols’ '
 'filings, only appearing in Scranton filings. Scranton’s 2021 filing shows an '
 'increase in liabilities of €59m relating to “advance payments from Grifols '
 'Worldwide Operations Ltd”, another transaction undisclosed in Grifols '
 'filings. Finally, Gotham argued that while Grifols’ CEO is hailed as a '
 'change in direction, he has actually been with Grifols since 2006, and was '
 'on the board at the time the suspect transactions occurred. Grifols put out '
 'a communique commenting upon “recent false information and speculations '
 'published by Gotham City Research regarding their accounting and financial '
 'disclosure”. In this, Grifols did deny and reject allegations of wrongful '
 'accounting or reporting practices of their consolidated financial '
 'statements, noting that their annual audits are conducted by one of the '
 'big-four audit firms. On Wednesday [Jan 10], the owner of Gotham City '
 'Research, General Industrial Partners, reduced its short position in Grifols '
 'to 0.06% from 0.6%. Job done. Grifols shares pared their two-day decline to '
 '18%. From 43% early Tuesday. Today [Jan 12], Grifols 5-year CDS widened back '
 'roughly 90bp, on concerns about the collapse of a $1.8B deal to sell a stake '
 'in Shanghai RAAS Blood Products to a Chinese player named Haier. The market '
 'fears a breakdown in the deal due to the turmoil ignited this week by '
 'Gotham. However, some other analysts express confidence that the deal w ill '
 'be closed in the coming months.')
result = await credit_outlook(market_comment)

pprint(result)
{'company_name': 'Grifols S.A.',
 'credit_outlook': 'negative',
 'main_risk_factor': 'Gotham allegations, deal failure'}

Not bad. Let’s now try something a bit harder but supported by LMQL: a while control flow.

We will try to have LMQL extract {(cause) => (consequence)} that could potentially lead to the default of the company, according to the content of the market comment.

@lmql.query()
async def causal_mechanism_bankruptcy(market_comment):
  '''lmql
    argmax
    "You are a credit analysis working at a prestigious hedge fund for a very busy portfolio manager."
    "You read the following market comment: {market_comment}, and you write for the portfolio manager a crisp causal explanation of the most likely way the company mentioned in the comment could default within the next couple of years."
    "The name of the company which is the main focus of this market comment is:[COMPANY_NAME]" where STOPS_AT(COMPANY_NAME, "\n")
    "Based on this market comment only, the most likely way this company could default within the next couple of years can be explained by the following causal mechanism:[CAUSAL_MECHANISM]"
    "Please, write the explanation of the causal mechanism leading to a potential default of the company (which should be the final consequence and noted 'DEFAULT' in the explanation). The explanation should be written in a simple format such as CAUSE_1 => CONSEQUENCE_1, CAUSE_2 => CONSEQUENCE_2, CAUSE_3 and CONSEQUENCE_2 => DEFAULT. 'DEFAULT' string is the final consequence of the explanation. The state of DEFAULT cannot be a cause, only a consequence. Each CAUSE_i and CONSEQUENCE_i should be short and no more than 5 words long."
    "A list of a cause followed by (and separated by the symbol '=>') its consequence with the format CAUSE_i => CONSEQUENCE_i that can yield to the default of a company):\n"
    causal_list = []
    CONSEQUENCE = ""
    while CONSEQUENCE.lstrip(' ').rstrip('\n') not in ['DEFAULT', 'Potential default']:
      "-[CAUSE] =>[CONSEQUENCE]\n" where STOPS_AT(CAUSE, "=>") and STOPS_AT(CONSEQUENCE, "\n")
      causal_list.append({
        "cause": CAUSE.lstrip(' ').rstrip(' =>'),
        "consequence": CONSEQUENCE.lstrip(' ').rstrip('\n')})
    return {
      "company_name": COMPANY_NAME.rstrip('\n').lstrip(' '),
      "causal_explanation": causal_list,
    }
  '''
market_comment = "Named after “nature” in Hebrew, Teva Pharmaceutical Industries Ltd [TEVA] is the largest generics lab and stands in the top 20 of global pharmas. Headquartered in Israel, Teva grew by acquisitions from 2000, and even launched a $40B bid for Mylan [2015]. 2017 was a pivotal year, as it saw Teva sell assets, slash divvy -75%, cut staff -25%, and market cap went from $60B+ [2016] to almost $10B. For CDS, this turning point saw a floor at 150bp. While today we approach this floor again, some analysts have argued that 2023 was another pivotal year. Indeed, during 2023, Teva managed to “resolve” [$4.25B] the opioids case, “resolve” [$225m] price-fixing case, continued to reduce net debt, got a new CEO and presented a new strategic plan for the coming years, and returned to revenue growth [1st revenue growth in 6 years]. At its May 2023 investor day, TEVA had said they expect to get back to IG over next 2-3 years, from current BB-/BB-/Ba2. TEVA just reported Q4 EBITDA $1,660m [est $1,374m] although there were chunky one-off upfront payments of $430m on a collaboration with Sanofi. Including these, TEVA ended the year with a net leverage 3.5x. Late last month [Jan 31], TEVA announced its intention to divest its API [active pharmaceutical ingredients] business TAPI, expected done by H1-25, this could take net leverage close but above 3x. Going forward, TEVA guided for FCF $1.7-2.0B this year [EBITDA $4.5-5.0B]. Bloomberg consensus seems more optimistic, with 2.3B penciled in, for both this year and next. Just like that. Now, TEVA still has a decent $20B+ of debt outstanding, ’24 and ’25 maturities seem within anticipated FCF, but the interesting one may be ’26 [$3.4B bonds maturing that year]."

pprint(market_comment)
('Named after “nature” in Hebrew, Teva Pharmaceutical Industries Ltd [TEVA] is '
 'the largest generics lab and stands in the top 20 of global pharmas. '
 'Headquartered in Israel, Teva grew by acquisitions from 2000, and even '
 'launched a $40B bid for Mylan [2015]. 2017 was a pivotal year, as it saw '
 'Teva sell assets, slash divvy -75%, cut staff -25%, and market cap went from '
 '$60B+ [2016] to almost $10B. For CDS, this turning point saw a floor at '
 '150bp. While today we approach this floor again, some analysts have argued '
 'that 2023 was another pivotal year. Indeed, during 2023, Teva managed to '
 '“resolve” [$4.25B] the opioids case, “resolve” [$225m] price-fixing case, '
 'continued to reduce net debt, got a new CEO and presented a new strategic '
 'plan for the coming years, and returned to revenue growth [1st revenue '
 'growth in 6 years]. At its May 2023 investor day, TEVA had said they expect '
 'to get back to IG over next 2-3 years, from current BB-/BB-/Ba2. TEVA just '
 'reported Q4 EBITDA $1,660m [est $1,374m] although there were chunky one-off '
 'upfront payments of $430m on a collaboration with Sanofi. Including these, '
 'TEVA ended the year with a net leverage 3.5x. Late last month [Jan 31], TEVA '
 'announced its intention to divest its API [active pharmaceutical '
 'ingredients] business TAPI, expected done by H1-25, this could take net '
 'leverage close but above 3x. Going forward, TEVA guided for FCF $1.7-2.0B '
 'this year [EBITDA $4.5-5.0B]. Bloomberg consensus seems more optimistic, '
 'with 2.3B penciled in, for both this year and next. Just like that. Now, '
 'TEVA still has a decent $20B+ of debt outstanding, ’24 and ’25 maturities '
 'seem within anticipated FCF, but the interesting one may be ’26 [$3.4B bonds '
 'maturing that year].')
result = await causal_mechanism_bankruptcy(market_comment)

pprint(result)
{'causal_explanation': [{'cause': 'Legal issues',
                         'consequence': 'Financial settlements'},
                        {'cause': 'Divestment of API business',
                         'consequence': 'Decrease in revenue/earnings'},
                        {'cause': 'High level of debt',
                         'consequence': 'Difficulty meeting obligations'},
                        {'cause': 'Downgraded credit ratings',
                         'consequence': 'Difficulty refinancing debt'},
                        {'cause': 'Debt maturing in 2026',
                         'consequence': 'Difficulty refinancing debt'},
                        {'cause': 'Inability to regain investment-grade status',
                         'consequence': 'Difficulty refinancing debt'},
                        {'cause': 'Legal issues and divestment of API business',
                         'consequence': 'Decrease in financial stability'},
                        {'cause': 'Decrease in revenue/earnings and '
                                  'lower-than-expected free cash flow',
                         'consequence': 'Difficulty meeting debt obligations'},
                        {'cause': 'Difficulty meeting obligations and '
                                  'difficulty refinancing debt',
                         'consequence': 'DEFAULT'}],
 'company_name': 'Teva Pharmaceutical Industries Ltd [TEVA].'}
market_comment = "As usual, Swedish companies reported ahead of most Europeans. Telefonaktiebolaget LM Ericsson [ERICB - Ba1 / BBB- / BBB-] is the company that has invented Bluetooth technology, they are one of the world’s biggest providers of 5G networking equipment, they own c60k patents. Ericsson CDS is a constituent of XOver since series s27. It was in the Main index before that, since series s16. Last month, Ericsson 5-year CDS widened +6bp on earnings day, which extended a series of 8 consecutive widenings on quarterly earnings day. This move was little however, if compared to the average +16bp move in the previous 7 releases. The market surely got accustomed to these downbeat releases [and to the rallies in between these releases], allowing Ericsson 5-year CDS to remain close to one-year tight, 120bp handle. Ericsson CEO warned that the market [outside of China] will continue to decline in 2024. In 2024, Ericsson expects a continued drop in mobile business but is ready for a turnaround. Q4 revenues fell by -17%, mainly due to a -23% decline in NA Networks. While India still contributed to growth, it slowed down notably. Ericsson predicts a global -4% decline in RAN market, offset by cloud software and services & enterprise. FCF decreased on lower EBIT, restructuring charges, and WC. Ericsson ended 2023 with SEK7.8b net cash, down from SEK23.3b at the end of 2022. 2024 is still young but it sounds like another sluggish year, with subdued spending from mobile service providers who have been slower than anticipated to roll out 5G. Longer term, Ericsson’s duopoly also risks being disrupted by ORAN [open radio access networks - operators can choose antennas/infrastructure vendors]. Despite all that, Ericsson confirmed SEK2.70/sh divvy. On the bright side of things, EBIT margin before restructuring charges has surpassed 10%, enabling management to maintain mid-term margin targets: EBITA [15-18%] FCF [9-12%]. Moreover, progress was made on the SEK12b cost savings plan, with 50% done in 2023. Finally, the $14B AT&T deal is hoped to increase revenues in H2. The latter points talk in favor of Ericsson, relative to its peer Nokia, which trades almost 20bp tighter."

pprint(market_comment)
('As usual, Swedish companies reported ahead of most Europeans. '
 'Telefonaktiebolaget LM Ericsson [ERICB - Ba1 / BBB- / BBB-] is the company '
 'that has invented Bluetooth technology, they are one of the world’s biggest '
 'providers of 5G networking equipment, they own c60k patents. Ericsson CDS is '
 'a constituent of XOver since series s27. It was in the Main index before '
 'that, since series s16. Last month, Ericsson 5-year CDS widened +6bp on '
 'earnings day, which extended a series of 8 consecutive widenings on '
 'quarterly earnings day. This move was little however, if compared to the '
 'average +16bp move in the previous 7 releases. The market surely got '
 'accustomed to these downbeat releases [and to the rallies in between these '
 'releases], allowing Ericsson 5-year CDS to remain close to one-year tight, '
 '120bp handle. Ericsson CEO warned that the market [outside of China] will '
 'continue to decline in 2024. In 2024, Ericsson expects a continued drop in '
 'mobile business but is ready for a turnaround. Q4 revenues fell by -17%, '
 'mainly due to a -23% decline in NA Networks. While India still contributed '
 'to growth, it slowed down notably. Ericsson predicts a global -4% decline in '
 'RAN market, offset by cloud software and services & enterprise. FCF '
 'decreased on lower EBIT, restructuring charges, and WC. Ericsson ended 2023 '
 'with SEK7.8b net cash, down from SEK23.3b at the end of 2022. 2024 is still '
 'young but it sounds like another sluggish year, with subdued spending from '
 'mobile service providers who have been slower than anticipated to roll out '
 '5G. Longer term, Ericsson’s duopoly also risks being disrupted by ORAN [open '
 'radio access networks - operators can choose antennas/infrastructure '
 'vendors]. Despite all that, Ericsson confirmed SEK2.70/sh divvy. On the '
 'bright side of things, EBIT margin before restructuring charges has '
 'surpassed 10%, enabling management to maintain mid-term margin targets: '
 'EBITA [15-18%] FCF [9-12%]. Moreover, progress was made on the SEK12b cost '
 'savings plan, with 50% done in 2023. Finally, the $14B AT&T deal is hoped to '
 'increase revenues in H2. The latter points talk in favor of Ericsson, '
 'relative to its peer Nokia, which trades almost 20bp tighter.')
result = await causal_mechanism_bankruptcy(market_comment)

pprint(result)
{'causal_explanation': [{'cause': 'Continued decline in global RAN market',
                         'consequence': 'Decrease in revenues'},
                        {'cause': 'Slower than anticipated rollout of 5G',
                         'consequence': 'Decrease in cash flow'},
                        {'cause': 'Potential disruption from ORAN',
                         'consequence': 'Decrease in revenues'},
                        {'cause': 'Decrease in revenues',
                         'consequence': 'Difficulty meeting financial '
                                        'obligations'},
                        {'cause': 'Difficulty meeting financial obligations',
                         'consequence': 'Struggle to maintain dividend'},
                        {'cause': 'Struggle to maintain dividend',
                         'consequence': 'Difficulty meeting margin targets'},
                        {'cause': 'Decrease in cash flow',
                         'consequence': 'Difficulty meeting financial '
                                        'obligations'},
                        {'cause': 'Net cash decrease',
                         'consequence': 'Difficulty meeting financial '
                                        'obligations'},
                        {'cause': 'Restructuring charges',
                         'consequence': 'Strain on financial position'},
                        {'cause': 'Difficulty meeting margin targets',
                         'consequence': 'Potential default'}],
 'company_name': 'Telefonaktiebolaget LM Ericsson (ERICB).'}
market_comment = "Intrum is a Sweden-based credit management services company with subsidiaries in Europe. They offer services covering the entire credit management chain, ranging from prospecting and segmenting to payment management services, collection and payment services [sales ledger, reminder, e-commerce, VAT refunds, debt collection, debt surveillance]. Intrum CDS is a constituent of XOver since s28, currently rated B2/BB/BB-. Last summer, Intrum reported available liquidity SEK 13b and SEK 61.3b total debt [bonds CPs PPs RCF] and was planning to cut leverage by scrapping 2024 dividend and exiting 3 additional markets completely [Czech Republic, Slovakia and Hungary]. This week, not only did we learn that the Eastern Europe exit was not guaranteed any longer either, but Intrum also agreed to sell part of its portfolio, to raise SEK8.2b [by H1 end]. This confirms rumours from December, and covers slightly more than a third of debt due by 2025 end. So, Intrum sold two thirds what could be their crown jewel assets. The assets they could sell, anyway. For 98% of Sept 30th book value. Retaining a 35% stake in the entity acquiring them. Cerberus owning the other 65%. And Intrum agreed to keep servicing the portfolio for at least 5 years. Even before the call Tuesday morning, this benefitted the very short end of the curve, but was already slight negative for the longer end and for the equity [FCF dilutive, increasing leverage]. While Tuesday morning started around 13.5% upfront [5-year / before the call], Intrum CDS had reached 18% upfront by noon, and widened a total +8pt over two sessions. Skepticism about achieving servicing targets, reduced RCF capacity, limited asset sales prospects going forward, are likely to keep Intrum CDS in the top 3 of widest names in crossover benchmark. Its now reverted tighter -2.5pt over the past two sessions, in a slight reversal. A successful RCF maturity extension is what could take it back further."

pprint(market_comment)
('Intrum is a Sweden-based credit management services company with '
 'subsidiaries in Europe. They offer services covering the entire credit '
 'management chain, ranging from prospecting and segmenting to payment '
 'management services, collection and payment services [sales ledger, '
 'reminder, e-commerce, VAT refunds, debt collection, debt surveillance]. '
 'Intrum CDS is a constituent of XOver since s28, currently rated B2/BB/BB-. '
 'Last summer, Intrum reported available liquidity SEK 13b and SEK 61.3b total '
 'debt [bonds CPs PPs RCF] and was planning to cut leverage by scrapping 2024 '
 'dividend and exiting 3 additional markets completely [Czech Republic, '
 'Slovakia and Hungary]. This week, not only did we learn that the Eastern '
 'Europe exit was not guaranteed any longer either, but Intrum also agreed to '
 'sell part of its portfolio, to raise SEK8.2b [by H1 end]. This confirms '
 'rumours from December, and covers slightly more than a third of debt due by '
 '2025 end. So, Intrum sold two thirds what could be their crown jewel assets. '
 'The assets they could sell, anyway. For 98% of Sept 30th book value. '
 'Retaining a 35% stake in the entity acquiring them. Cerberus owning the '
 'other 65%. And Intrum agreed to keep servicing the portfolio for at least 5 '
 'years. Even before the call Tuesday morning, this benefitted the very short '
 'end of the curve, but was already slight negative for the longer end and for '
 'the equity [FCF dilutive, increasing leverage]. While Tuesday morning '
 'started around 13.5% upfront [5-year / before the call], Intrum CDS had '
 'reached 18% upfront by noon, and widened a total +8pt over two sessions. '
 'Skepticism about achieving servicing targets, reduced RCF capacity, limited '
 'asset sales prospects going forward, are likely to keep Intrum CDS in the '
 'top 3 of widest names in crossover benchmark. Its now reverted tighter '
 '-2.5pt over the past two sessions, in a slight reversal. A successful RCF '
 'maturity extension is what could take it back further.')
result = await causal_mechanism_bankruptcy(market_comment)

pprint(result)
{'causal_explanation': [{'cause': 'Insufficient liquidity',
                         'consequence': 'Difficulty meeting debt obligations'},
                        {'cause': 'High debt levels',
                         'consequence': 'Difficulty meeting debt obligations'},
                        {'cause': 'Inability to cut leverage',
                         'consequence': 'Difficulty meeting debt obligations'},
                        {'cause': 'Inability to exit markets',
                         'consequence': 'Difficulty meeting debt obligations'},
                        {'cause': 'Sale of portfolio at discounted price',
                         'consequence': 'Difficulty meeting debt obligations'},
                        {'cause': 'Retaining stake in acquiring entity',
                         'consequence': 'Difficulty meeting debt obligations'},
                        {'cause': 'Inability to meet servicing targets',
                         'consequence': 'Difficulty meeting debt obligations'},
                        {'cause': 'Reduced RCF capacity',
                         'consequence': 'Difficulty meeting debt obligations'},
                        {'cause': 'Limited asset sales prospects',
                         'consequence': 'Difficulty meeting debt obligations'},
                        {'cause': 'Widening of CDS',
                         'consequence': 'Difficulty meeting debt obligations'},
                        {'cause': 'Failure to extend RCF maturity',
                         'consequence': 'Difficulty meeting debt obligations'},
                        {'cause': 'Inability to improve financial position',
                         'consequence': 'Difficulty meeting debt obligations'},
                        {'cause': 'Difficulty meeting debt obligations',
                         'consequence': 'DEFAULT'}],
 'company_name': 'Intrum'}
market_comment = "CMA CGM SA [CMACG] is the #3 global shipping co. The services they provide include vessel/container fleet management, freight delivery, logistics, cargo cruises. CMA CGM is privately controlled by the Saade family [founders]. CMA CGM is HQ’d in Marseille and sponsors the [un]beloved OM football club. CMA CGM CDS has been in CrossOver indices from s25 to s38. After reaching 50% upfront at the peak of the covid financial crisis, CMA CGM CDS tightened massively and continuously, with conservative balance-sheet management coupled with surging earnings in the subsequent 2 years, thanks to high freight rates and saturated supply chains. While CMA CGM had less than €1.7B cash at EoY-20, they reported €11.3B cash at EoY-22. Jan 30 last year, CMA-CGM 5-year CDS spread squeezed tighter -110bp to 285bp, after reports that they’d redeem €525M 7.5% 26s at 103.75. Some analysts at the time noted CMACG CDS might find itself without any deliverable obligation, temporarily orphan. Since then, CMA CGM has not come back to the market, but still guarantees c€100m Fenix Marine debt, c€80m first lien secured loans at SCI Tour d’Arenc, on top of the €200m+ first lien secured loans at CMA CGM SA. Last May, CMA CGM Group granted a put option to the Bolloré Group to sell the transport and logistics operations of Bolloré Logistics. CMA CGM then started reporting significantly lower net income [$2B Q1-23 from $7B+ Q1-22] marking the end of two golden years. And last July, the Bolloré Group announced that it signed the share purchase agreement to sell 100% of Bolloré Logistics to the CMA CGM Group, purchase price €4.65B ex net debt, completion subject to antitrust and foreign investment clearances. In much smaller acquisitions, the Saade family has taken a 10% stake in French broadcaster M6, a stake in online media Brut and bought newspaper La Tribune, regional newspaper La Provence. June last year, Moody’s took CMA CGM's long-term corporate family rating up one notch to Ba1, with a stable outlook [from positive], praising continued high FCF generation used to fund both logistics and terminals acquisitions, as well as debt reduction, strengthening B/S. During H2-23 and to date, the open interest reported at clearing houses on CMA CGM CDS, has been about halved, now just shy of €400m across Ice Clear and LCH, and across all maturities, highlighting the depth of the short cutting enterprise that’s been taking place, although the fact that this name is not in CrossOver indices since series s38 surely played a role. Aside October-last-year macro weakness, there has been NO exit door for shorts on CMA CGM CDS. More recently, the fact that several shipping companies announced a pause on Red Sea passages [following USUK/Houthi local war -- inducing a c30% significant extension via South Africa] is likely to boost container companies’ earnings prospects. On that, Reuters has reported that CMA CGM’s Asia-Med freight rates had soared by up to 100% [!] as of this past Monday, compared to Monday Jan 1st. Absent a short resolution in the Red Sea, 200bp does not feel like a solid floor."

pprint(market_comment)
('CMA CGM SA [CMACG] is the #3 global shipping co. The services they provide '
 'include vessel/container fleet management, freight delivery, logistics, '
 'cargo cruises. CMA CGM is privately controlled by the Saade family '
 '[founders]. CMA CGM is HQ’d in Marseille and sponsors the [un]beloved OM '
 'football club. CMA CGM CDS has been in CrossOver indices from s25 to s38. '
 'After reaching 50% upfront at the peak of the covid financial crisis, CMA '
 'CGM CDS tightened massively and continuously, with conservative '
 'balance-sheet management coupled with surging earnings in the subsequent 2 '
 'years, thanks to high freight rates and saturated supply chains. While CMA '
 'CGM had less than €1.7B cash at EoY-20, they reported €11.3B cash at EoY-22. '
 'Jan 30 last year, CMA-CGM 5-year CDS spread squeezed tighter -110bp to '
 '285bp, after reports that they’d redeem €525M 7.5% 26s at 103.75. Some '
 'analysts at the time noted CMACG CDS might find itself without any '
 'deliverable obligation, temporarily orphan. Since then, CMA CGM has not come '
 'back to the market, but still guarantees c€100m Fenix Marine debt, c€80m '
 'first lien secured loans at SCI Tour d’Arenc, on top of the €200m+ first '
 'lien secured loans at CMA CGM SA. Last May, CMA CGM Group granted a put '
 'option to the Bolloré Group to sell the transport and logistics operations '
 'of Bolloré Logistics. CMA CGM then started reporting significantly lower net '
 'income [$2B Q1-23 from $7B+ Q1-22] marking the end of two golden years. And '
 'last July, the Bolloré Group announced that it signed the share purchase '
 'agreement to sell 100% of Bolloré Logistics to the CMA CGM Group, purchase '
 'price €4.65B ex net debt, completion subject to antitrust and foreign '
 'investment clearances. In much smaller acquisitions, the Saade family has '
 'taken a 10% stake in French broadcaster M6, a stake in online media Brut and '
 'bought newspaper La Tribune, regional newspaper La Provence. June last year, '
 "Moody’s took CMA CGM's long-term corporate family rating up one notch to "
 'Ba1, with a stable outlook [from positive], praising continued high FCF '
 'generation used to fund both logistics and terminals acquisitions, as well '
 'as debt reduction, strengthening B/S. During H2-23 and to date, the open '
 'interest reported at clearing houses on CMA CGM CDS, has been about halved, '
 'now just shy of €400m across Ice Clear and LCH, and across all maturities, '
 'highlighting the depth of the short cutting enterprise that’s been taking '
 'place, although the fact that this name is not in CrossOver indices since '
 'series s38 surely played a role. Aside October-last-year macro weakness, '
 'there has been NO exit door for shorts on CMA CGM CDS. More recently, the '
 'fact that several shipping companies announced a pause on Red Sea passages '
 '[following USUK/Houthi local war -- inducing a c30% significant extension '
 'via South Africa] is likely to boost container companies’ earnings '
 'prospects. On that, Reuters has reported that CMA CGM’s Asia-Med freight '
 'rates had soared by up to 100% [!] as of this past Monday, compared to '
 'Monday Jan 1st. Absent a short resolution in the Red Sea, 200bp does not '
 'feel like a solid floor.')
result = await causal_mechanism_bankruptcy(market_comment)

pprint(result)
{'causal_explanation': [{'cause': 'High debt',
                         'consequence': 'Insufficient cash flow'},
                        {'cause': 'Reliance on unsustainable earnings',
                         'consequence': 'Decrease in earnings'},
                        {'cause': 'Recent investments and acquisitions',
                         'consequence': 'Strain on balance sheet'},
                        {'cause': 'Pause on Red Sea passages',
                         'consequence': 'Decrease in earnings'},
                        {'cause': 'Low open interest in CDS contracts',
                         'consequence': 'Decrease in creditworthiness'},
                        {'cause': 'Decrease in creditworthiness',
                         'consequence': 'Increase in likelihood of default'},
                        {'cause': 'Insufficient cash flow and strain on '
                                  'balance sheet',
                         'consequence': 'DEFAULT'}],
 'company_name': 'CMA CGM SA.'}
market_comment = "Founded in 1909 as a small family-run clinical analysis laboratory in Barcelona, Grifols S.A. is now a global pharma/chemical manufacturer, European leader as producer of blood plasma-based products. Grifols also supply devices, instruments, and reagents for clinical testing laboratories. Rated Caa1/B-/B+ Grifols has its CDS in all CrossOver indices since vintage s28 included. COVID had been the primary driver of reduced plasma volumes, and started a new era for Grifols CDS. EBITDA margin remained strong 25% [20] 20% [21] but COVID net impact on EBITDA was -€500m [lower plasma volumes -€420m] and net leverage increased in 2021 off strategic acquisitions [€520m]. Now valued €5.5B in the stock market, Grifols had reported €10B long term debt as of 2022 end. They have two outstanding bonds totaling €2B due 2025, the next major bonds maturity year being 2027 [roughly another €2B]. In June 2022, Grifols outperformed after a weak H1 [300bp -> 600bp] and Grifols stocks fell, as they were reported to be in talks to raise €2B equity. This was seen as showing a shift in Grifols family vision about leverage and control. However this was after leverage reduction had been guided in February 2022. At the time net debt €5.8B [end 2021] net leverage 5.4x, liquidity €1.3B cash €0.7B. Last June 14, Grifols 5-year CDS tightened -70bp to 430bp, as Grifols may sell off assets including the 26% in Shanghai RAAS it bought in 2019. Grifols had entered a strategic alliance with the Chinese group in 2020. Grifols SA said that they would expect to receive $1.5B if a deal goes through, boosting their debt cutting effort. The beautiful rally ended THIS WEEK. On Tuesday [Jan 9] Gotham City Research LLC stated that Grifols manipulates reported debt & EBITDA to artificially reduce reported leverage to 6x, which they believe is closer to 12x. Gotham argued that both Grifols and Scranton Enterprises [a Grifols family vehicle] fully consolidate BPC + Haema onto their financial statements, a deceptive and incorrect treatment. Gotham said that should their estimate of Grifols’ true leverage be correct, the company should face notably higher financing costs, and they believe that Grifols equities are uninvestable, “likely zero”. Gotham said Grifols fully consolidates both Haema and BPC Plasma, despite owning 0% of each company, Haema + BPC are material to Grifols as they account for c40% of Grifols earnings from non-controlling interests, Scranton Enterprises also fully consolidates BPC Plasma and Haema, these entities’ earnings appear to account for >100% of Scranton’s earnings, while Scranton owns 8.4% of Grifols. At a lesser level, Gotham claimed that Grifols lent Scranton $95m in 2018, a loan seeming tied to the BPC/Haema transaction, yet this loan was undisclosed in Grifols’ filings, only appearing in Scranton filings. Scranton’s 2021 filing shows an increase in liabilities of €59m relating to “advance payments from Grifols Worldwide Operations Ltd”, another transaction undisclosed in Grifols filings. Finally, Gotham argued that while Grifols’ CEO is hailed as a change in direction, he has actually been with Grifols since 2006, and was on the board at the time the suspect transactions occurred. Grifols put out a communique commenting upon “recent false information and speculations published by Gotham City Research regarding their accounting and financial disclosure”. In this, Grifols did deny and reject allegations of wrongful accounting or reporting practices of their consolidated financial statements, noting that their annual audits are conducted by one of the big-four audit firms. On Wednesday [Jan 10], the owner of Gotham City Research, General Industrial Partners, reduced its short position in Grifols to 0.06% from 0.6%. Job done. Grifols shares pared their two-day decline to 18%. From 43% early Tuesday. Today [Jan 12], Grifols 5-year CDS widened back roughly 90bp, on concerns about the collapse of a $1.8B deal to sell a stake in Shanghai RAAS Blood Products to a Chinese player named Haier. The market fears a breakdown in the deal due to the turmoil ignited this week by Gotham. However, some other analysts express confidence that the deal w ill be closed in the coming months."

pprint(market_comment)
('Founded in 1909 as a small family-run clinical analysis laboratory in '
 'Barcelona, Grifols S.A. is now a global pharma/chemical manufacturer, '
 'European leader as producer of blood plasma-based products. Grifols also '
 'supply devices, instruments, and reagents for clinical testing laboratories. '
 'Rated Caa1/B-/B+ Grifols has its CDS in all CrossOver indices since vintage '
 's28 included. COVID had been the primary driver of reduced plasma volumes, '
 'and started a new era for Grifols CDS. EBITDA margin remained strong 25% '
 '[20] 20% [21] but COVID net impact on EBITDA was -€500m [lower plasma '
 'volumes -€420m] and net leverage increased in 2021 off strategic '
 'acquisitions [€520m]. Now valued €5.5B in the stock market, Grifols had '
 'reported €10B long term debt as of 2022 end. They have two outstanding bonds '
 'totaling €2B due 2025, the next major bonds maturity year being 2027 '
 '[roughly another €2B]. In June 2022, Grifols outperformed after a weak H1 '
 '[300bp -> 600bp] and Grifols stocks fell, as they were reported to be in '
 'talks to raise €2B equity. This was seen as showing a shift in Grifols '
 'family vision about leverage and control. However this was after leverage '
 'reduction had been guided in February 2022. At the time net debt €5.8B [end '
 '2021] net leverage 5.4x, liquidity €1.3B cash €0.7B. Last June 14, Grifols '
 '5-year CDS tightened -70bp to 430bp, as Grifols may sell off assets '
 'including the 26% in Shanghai RAAS it bought in 2019. Grifols had entered a '
 'strategic alliance with the Chinese group in 2020. Grifols SA said that they '
 'would expect to receive $1.5B if a deal goes through, boosting their debt '
 'cutting effort. The beautiful rally ended THIS WEEK. On Tuesday [Jan 9] '
 'Gotham City Research LLC stated that Grifols manipulates reported debt & '
 'EBITDA to artificially reduce reported leverage to 6x, which they believe is '
 'closer to 12x. Gotham argued that both Grifols and Scranton Enterprises [a '
 'Grifols family vehicle] fully consolidate BPC + Haema onto their financial '
 'statements, a deceptive and incorrect treatment. Gotham said that should '
 'their estimate of Grifols’ true leverage be correct, the company should face '
 'notably higher financing costs, and they believe that Grifols equities are '
 'uninvestable, “likely zero”. Gotham said Grifols fully consolidates both '
 'Haema and BPC Plasma, despite owning 0% of each company, Haema + BPC are '
 'material to Grifols as they account for c40% of Grifols earnings from '
 'non-controlling interests, Scranton Enterprises also fully consolidates BPC '
 'Plasma and Haema, these entities’ earnings appear to account for >100% of '
 'Scranton’s earnings, while Scranton owns 8.4% of Grifols. At a lesser level, '
 'Gotham claimed that Grifols lent Scranton $95m in 2018, a loan seeming tied '
 'to the BPC/Haema transaction, yet this loan was undisclosed in Grifols’ '
 'filings, only appearing in Scranton filings. Scranton’s 2021 filing shows an '
 'increase in liabilities of €59m relating to “advance payments from Grifols '
 'Worldwide Operations Ltd”, another transaction undisclosed in Grifols '
 'filings. Finally, Gotham argued that while Grifols’ CEO is hailed as a '
 'change in direction, he has actually been with Grifols since 2006, and was '
 'on the board at the time the suspect transactions occurred. Grifols put out '
 'a communique commenting upon “recent false information and speculations '
 'published by Gotham City Research regarding their accounting and financial '
 'disclosure”. In this, Grifols did deny and reject allegations of wrongful '
 'accounting or reporting practices of their consolidated financial '
 'statements, noting that their annual audits are conducted by one of the '
 'big-four audit firms. On Wednesday [Jan 10], the owner of Gotham City '
 'Research, General Industrial Partners, reduced its short position in Grifols '
 'to 0.06% from 0.6%. Job done. Grifols shares pared their two-day decline to '
 '18%. From 43% early Tuesday. Today [Jan 12], Grifols 5-year CDS widened back '
 'roughly 90bp, on concerns about the collapse of a $1.8B deal to sell a stake '
 'in Shanghai RAAS Blood Products to a Chinese player named Haier. The market '
 'fears a breakdown in the deal due to the turmoil ignited this week by '
 'Gotham. However, some other analysts express confidence that the deal w ill '
 'be closed in the coming months.')
result = await causal_mechanism_bankruptcy(market_comment)

pprint(result)
{'causal_explanation': [{'cause': 'Decrease in plasma volumes',
                         'consequence': 'Negative impact on EBITDA'},
                        {'cause': 'Negative impact on EBITDA',
                         'consequence': 'Increase in net leverage'},
                        {'cause': 'Increase in net leverage',
                         'consequence': 'Decrease in liquidity'},
                        {'cause': 'Decrease in liquidity',
                         'consequence': 'Difficulty in meeting debt '
                                        'obligations'},
                        {'cause': 'Difficulty in meeting debt obligations',
                         'consequence': 'Potential default on debt'},
                        {'cause': 'Allegations of deceptive accounting '
                                  'practices',
                         'consequence': 'Market turmoil'},
                        {'cause': 'Market turmoil',
                         'consequence': 'Decline in stock price'},
                        {'cause': 'Decline in stock price',
                         'consequence': 'Increase in CDS'},
                        {'cause': 'Failure of $1.8B deal',
                         'consequence': 'Difficulty in managing debt'},
                        {'cause': 'Difficulty in managing debt',
                         'consequence': 'Potential default on debt'},
                        {'cause': 'Inability to secure new financing',
                         'consequence': 'Potential default on debt'},
                        {'cause': 'Potential default on debt',
                         'consequence': 'DEFAULT'}],
 'company_name': 'Grifols S.A.'}

Conclusion: In this blog post, we explored the application of LMQL, a SQL-like language for interacting with large language models (LLMs), focusing on its practical use in analyzing market comments. The examples provided demonstrate how LMQL can be employed to extract and structure specific information from textual data: LMQL enhances one’s ability to manage the output format of language models, which can occasionally be overly ‘creative’. This facilitates the integration of LLM outputs into conventional information systems that require structured inputs.