C++ for Quants
  • Home
  • News
  • Contact
  • About
Author

Clement D.

Clement D.

News

Precious Metals Rally: Experts Analyze Market Trends for Investors

by Clement D. January 15, 2026

“Uncertainty looms large as investors navigate the turbulent markets,” says renowned economist Paul Krugman. In today’s financial landscape, risk and opportunity coexist, as evidenced by the recent rally in precious metals. Bloomberg’s MLIV team delves into the factors driving this surge, offering insights that may guide investors in navigating the uncertain terrain.

Later in the article, we’ll explore how geopolitical tensions, such as the potential for another U.S. attack on Iran, could impact global markets. Additionally, we’ll examine the European military’s presence in Greenland and the implications for the region’s dynamics. Stay tuned as we unpack these developments and their potential impact on your investment decisions.

🎥 Precious Metals Have Rallied Too Quickly: 3-Minutes MLIV (Bloomberg)

The video provides a concise, analytical breakdown of key market themes for analysts and investors. The panel discusses the recent rally in precious metals, noting that it may have occurred too quickly. They also touch on critical minerals tariffs, the rotation in small-cap stocks, and the potential for an AI bubble amidst ongoing inflationary pressures. The discussion offers valuable insights for those tracking the latest developments in financial markets and their broader implications.


🎥 Trump Signals He’ll Hold Off Another Attack on Iran for Now | Daybreak Europe 1/15/2026 (Bloomberg)

On today’s episode of Bloomberg Daybreak Europe, the focus was on Donald Trump’s signal that he may hold off on attacking Iran for now, after being reassured that Tehran would stop killing people involved in protests. This development, along with Iran temporarily closing airspace around its capital, had implications for the oil market, as Brent crude prices slid. Additionally, the show discussed a “fundamental disagreement” between Denmark’s foreign minister and the US after a meeting in Washington, as well as Germany’s plans to join other European nations in an exploratory mission this week. The program also highlighted TSMC’s strong profit growth, with a 46% surge in net profit in 2025 and a 35% increase in fourth-quarter profits, driven by booming demand for AI hardware. The episode featured interviews with Mike Sfraga, Interim Chancellor at the University of Alaska Fairbanks, and Charu Chanana, Chief Investment Strategist at Saxo.


🎥 Trump Holds Back on Iran; European Military In Greenland | Horizons Middle East & Africa 1/15/2025 (Bloomberg)

The video provides a comprehensive update on key developments in the Middle East and Africa region. It begins by reporting on the slump in oil prices after US President Donald Trump signals he may hold off on attacking Iran for now. The clip then transitions to the arrival of German military personnel in Greenland, as European nations respond to US threats, with Denmark stating that a fundamental disagreement remains after meeting with US officials. The presentation also covers Mozambique’s stance on renegotiating its debt, indicating that discussions will only commence after a new program is agreed with the IMF. The video touches on a range of other topics, including TSMC’s profit beats, the commodities slump, the ongoing Iran unrest, and the progress of the NBA Africa League franchise plans.


🎥 Trump Doubles Down on Greenland Ambitions | Insight with Haslinda Amin 01/15/2026 (Bloomberg)

In the latest episode of “Insight with Haslinda Amin,” viewers are given a comprehensive analysis of President Trump’s continued ambitions to acquire Greenland. The program features in-depth interviews with prominent leaders, including a senator and a foreign policy expert, who provide valuable insights into the geopolitical implications of this ongoing saga. Additionally, the show covers a range of other pressing business and financial news, including the upcoming earnings report from TSMC, the outlook for the technology sector, and the potential impact of the US government’s visa policy changes. Institutional investors will find this episode of “Insight with Haslinda Amin” to be a must-watch, as it delivers a serious, factual, and action-oriented assessment of the key developments shaping the global economic landscape.


♟️ Interested in More?

  • Read the latest financial news: c++ for quants news.
January 15, 2026 0 comments
News

Market Moves, Geopolitics, and Fed Watch: Top Finance News

by Clement D. January 13, 2026

Contrary to expectations, the markets have displayed a remarkable resilience in the face of recent economic challenges. As the S&P 500 and Dow Jones Industrial Average recover from earlier losses, a closer examination of the data reveals intriguing patterns and potential signals for investors.

In our upcoming video, “Today on Taking Stock | S&P 500, Dow Recover From Earlier Losses,” we’ll dive deeper into the market dynamics and explore the factors driving this unexpected rebound. Additionally, in the video “Japan Politics Matter More Than Fed, CPI – 3-Minute MLIV,” our experts will provide insights on how the ongoing political landscape in Japan and the latest economic data are shaping investor sentiment.

Furthermore, the potential impact of the Trump administration’s proposed 25% tariff on countries doing business with Iran, as discussed in the “Trump Vows 25% Tariff on Countries Doing Business With Iran | Daybreak Europe 1/13/2026” video, could introduce new variables into the market equation. Coupled with the GOP’s backlash against the Federal Reserve, as highlighted in the “Japan Snap Election; GOP Fed Backlash; Trump’s Iran Tariff | Horizons Middle East & Africa 1/13/2025” video, these developments warrant close attention from quantitative analysts and investors alike.

🎥 Today on Taking Stock | S&P 500, Dow Recover From Earlier Losses (New York Stock Exchange)

The video in question showcases the resilience of the broader market, as the S&P 500 and Dow Jones Industrial Average managed to recover from earlier losses during the trading session. While the initial market conditions may have presented potential vulnerabilities, the ability of these key indices to rebound suggests a degree of inherent resilience within the financial system. However, a risk analyst would be prudent to consider the underlying factors that contributed to the earlier declines, such as macroeconomic conditions, geopolitical tensions, or sector-specific challenges, as these could still pose exposures that warrant further examination. Nonetheless, the video’s narrative highlights the market’s capacity to adapt and navigate through periods of volatility, a crucial characteristic for investors seeking to manage their risk profiles effectively.


🎥 Japan Politics Matter More Than Fed, CPI – 3-Minute MLIV (Bloomberg)

The video provides a clear and concise overview of the key financial themes impacting the markets. It highlights the market’s reaction to the Federal Reserve’s comments, the ongoing concerns around inflation and the U.S. CPI data, as well as the significant developments in Japan’s bond market and the potential for a snap election. These factors hold significant implications for analysts and investors, underscoring the importance of closely monitoring the evolving political and economic landscape.


🎥 Trump Vows 25% Tariff on Countries Doing Business With Iran | Daybreak Europe 1/13/2026 (Bloomberg)

In a move that could escalate trade tensions, former U.S. President Donald Trump vowed to impose a 25% tariff on goods from any country doing business with Iran. This decision risks upending America’s trade truce with China, the world’s top buyer of Iranian oil. The Trump administration’s probe into the central bank also triggered a backlash in Washington, with key Republicans warning that the Fed’s independence is being eroded. Separately, the Japanese yen weakened to its lowest level since July 2024, and stocks soared, following a report that Prime Minister Sanae Takaichi plans to call a snap election to solidify support for her hawkish political stance and pro-stimulus policies.


🎥 Japan Snap Election; GOP Fed Backlash; Trump’s Iran Tariff | Horizons Middle East & Africa 1/13/2025 (Bloomberg)

As market strategists gather for their morning call, the focus turns to a flurry of geopolitical and economic developments across the Middle East and Africa. Japanese stocks have jumped, with the yen weakening to a July 2024 low, following reports that the prime minister intends to call a snap election. Meanwhile, the Trump administration’s probe into the Federal Reserve has triggered a backlash in Washington, with key Republicans voicing their concerns. And in a bold move, President Trump has vowed new tariffs on countries doing business with Iran, effective immediately. Guests including Alexandre Tavazzi from Pictet Wealth Management, William Roebuck from the Arab Gulf States Institute, and Daan Struyven from Goldman Sachs provide their insights on these unfolding events and their potential implications for the region.


♟️ Interested in More?

  • Read the latest financial news: c++ for quants news.
January 13, 2026 0 comments
News

Geopolitics, Oil, and Risk: 3-Minute MLIV Insights for Investors

by Clement D. January 8, 2026

Geopolitical Tensions and Market Volatility: Key Themes for Finance Professionals

In today’s complex global landscape, finance professionals must stay attuned to the interplay between geopolitics and market dynamics. As discussed in the “Geopolitics Needs Policy to Move Risk: 3-Minute MLIV” video, factors such as the ongoing situation in Venezuela and the potential impact of Iran protests require careful analysis and strategic consideration.

Additionally, the “US To Control Venezuelan Oil ‘Indefinitely’; Iran Protests | Horizons Middle East & Africa 1/8/2026” video sheds light on the U.S. government’s plans to exert control over Venezuela’s oil exports, a development that could have significant implications for global energy markets.

Furthermore, the “ICE Minneapolis Shooting & Trump Demands More Defense Spending | Daybreak Europe 1/8/2026” video highlights the potential for geopolitical events, such as the ICE shooting in Minneapolis, to influence market sentiment and volatility.

To round out the discussion, the “Fun Quant Interview Question #quantinterviews” video presents a thought-provoking quantitative challenge that finance professionals may encounter in their career development.

🎥 Geopolitics Needs Policy to Move Risk: 3-Minute MLIV (Bloomberg)

The video’s thoughtful examination of the interplay between geopolitics and economic policy offers valuable insights for analysts and investors navigating today’s complex market landscape. By breaking down key themes such as the impact of Trump policy changes, the influence of AI and tech stocks on inflation, and China’s regulatory decisions, the panel provides a nuanced perspective on the multifaceted factors shaping global markets. As the world grapples with heightened geopolitical tensions, this insightful discussion underscores the critical importance of tailored policy responses to effectively manage and mitigate emerging risks.


🎥 US To Control Venezuelan Oil ‘Indefinitely’; Iran Protests | Horizons Middle East & Africa 1/8/2026 (Bloomberg)

The U.S. plans to indefinitely control future sales of Venezuelan oil, with President Donald Trump stating that the country will use the revenue only to purchase U.S.-made goods. Additionally, Bloomberg News has learned that Russia targeted South African video gamers as part of a recruitment drive for its war in Ukraine. In Iran, the president has ordered security forces not to target peaceful protesters, while Saudi Arabia’s Tadawul All Share Index jumped as much as 2.5% on Wednesday. Furthermore, Samsung reported that its fourth-quarter profit more than tripled to a record high, thanks to AI’s impact on the memory market.


🎥 ICE Minneapolis Shooting & Trump Demands More Defense Spending | Daybreak Europe 1/8/2026 (Bloomberg)

In the latest episode of Bloomberg’s Daybreak Europe, the program tackled several key financial themes with significant implications. President Trump’s demand for a more than 50% increase in the U.S. military budget to $1.5 trillion, along with his threat to defense companies over shareholder payouts, underscores the administration’s focus on bolstering national defense. Meanwhile, the Trump administration’s plan to control future sales of Venezuelan oil and hold the proceeds in U.S. accounts signals a continued effort to exert financial pressure on the Maduro regime. Additionally, the protests in Minneapolis following the shooting of a woman by an Immigration and Customs Enforcement officer have deepened the ongoing divisions in the country, with the mayor calling on ICE to leave the city. These developments, combined with updates on the global markets and insights from industry experts, provide a comprehensive overview of the financial landscape.


🎥 Fun Quant Interview Question #quantinterviews (Quant Prof)

In this strategic memo, we present a concise analysis of a video that addresses a common quantitative interview question. The video offers a thought-provoking challenge, providing decision-makers with valuable insights into the problem-solving abilities of potential candidates. The content is presented in a formal, succinct manner, highlighting the key elements that would be of interest to finance professionals evaluating prospective hires. This video serves as a useful tool in the assessment of quantitative skills, enabling informed decision-making in the recruitment process. By addressing this type of interview question, organizations can better identify candidates with the analytical acumen required to succeed in the dynamic finance industry.


♟️ Interested in More?

  • Read the latest financial news: c++ for quants news.
January 8, 2026 0 comments
News

Equities Rise, Greenland Alerts, Nvidia’s Chips: Digest Key Finance News

by Clement D. January 6, 2026

The Rise of the New Financial Frontier: Navigating the Evolving Landscape

The finance world has long been a bastion of tradition, but the tides are turning as we enter a new era of unprecedented change. This article will delve into the emerging trends and transformative forces that are reshaping the very foundations of the industry, setting the stage for a future where the rules of the game are being rewritten.

[Reference to the videos: The insights and analysis presented in the videos “Equities to Rise Not Just on Asia Tech: 3-Minute MLIV,” “Greenland on Alert After US Venezuela Move & Danish PM NATO Warning | 1/6/2026,” “Lebanon’s Economy & Trade Minister; Nvidia’s Rubin Chips | Horizons Middle East and Africa 1/6/2026,” and “Nvidia’s CES AI Reveal Fuels Global Tech Optimism | Insight with Haslinda Amin 01/06/2026” will provide a valuable context for understanding the broader trends and implications discussed in this article.]

🎥 Equities to Rise Not Just on Asia Tech: 3-Minute MLIV (Bloomberg)

In a concise and data-driven analysis, the Bloomberg MLIV team, including Anna Edwards, Guy Johnson, Tom Mackenzie, and Skylar Montgomery Koning, unpacks the key themes impacting analysts and investors on “The Opening Trade.” The discussion covers the broader market outlook, with a focus on the potential for equities to rise beyond just the Asian tech sector. The experts delve into the 2026 growth projections and the dynamics of the dollar’s performance against the euro, providing valuable insights for market participants.


🎥 Greenland on Alert After US Venezuela Move & Danish PM NATO Warning | 1/6/2026 (Bloomberg)

The Danish Prime Minister has warned that a U.S. attack on Greenland would lead to the end of the NATO alliance. This comes after the recent raid on Caracas, which has resulted in Delcy Rodríguez being sworn in as the acting president of Venezuela. Nicolás Maduro has also pleaded not guilty to drug charges in his first court appearance in the U.S. Meanwhile, Nvidia’s CEO has announced that the company’s highly-anticipated new artificial intelligence chips are nearing release, which are expected to speed up AI development. The report also covers the ongoing unrest in Venezuela, the potential impact on the U.S.-GCC relationship, and the strong performance of Asian stocks.


🎥 Lebanon’s Economy & Trade Minister; Nvidia’s Rubin Chips | Horizons Middle East and Africa 1/6/2026 (Bloomberg)

As an investment strategist, I would highlight the key risks, opportunities, and market sentiment surrounding the topics covered in this video. While Venezuela’s political instability and the US charges against Maduro pose significant risks, the potential restructuring of Ethiopia’s bonds could present a strategic investment opportunity. Additionally, the impending release of Nvidia’s highly-anticipated Rubin data center chips may generate positive market sentiment, particularly within the technology sector. However, the ongoing challenges in Lebanon’s economy, as discussed by the country’s Economy and Trade Minister, could create uncertainty for investors. Overall, this video offers a diverse range of financial and geopolitical developments that warrant close monitoring by investors seeking to navigate the complex landscape of the Middle East and Africa region.


🎥 Nvidia’s CES AI Reveal Fuels Global Tech Optimism | Insight with Haslinda Amin 01/06/2026 (Bloomberg)

Nvidia’s CES AI Reveal Fuels Global Tech Optimism

The video segment from Insight with Haslinda Amin provides a quantitative insight into the impact of Nvidia’s latest AI announcements at CES 2026. The data highlights a clear pattern of Asian stocks rallying, led by a surge in the tech sector, as investors respond positively to Nvidia’s unveiling of new AI tools for autonomous vehicles and robotics. This statistical signal suggests that Nvidia’s advancements are fueling broader optimism in the global tech landscape, potentially signaling opportunities for investors to capitalize on the AI boom.


♟️ Interested in More?

  • Read the latest financial news: c++ for quants news.
January 6, 2026 0 comments
calculate delta with finite differences
Greeks

Calculate Delta by Finite Differences

by Clement D. January 2, 2026

How to calculate delta by finite differences? In quantitative finance, Delta measures how sensitive an instrument’s value is to changes in the underlying price.

where VV is the value of the instrument and SS is the price of the underlying.

In practical terms, Delta answers a simple question:

If the underlying price moves slightly, how much does the price of my instrument move?

A Delta of 0.5 means that a one-unit increase in the underlying price increases the instrument’s value by roughly half a unit. A Delta close to 1 behaves like the underlying itself, while a Delta near 0 barely reacts at all.

This interpretation makes Delta central to both pricing and risk management. Traders use it to hedge exposure, risk systems use it to aggregate sensitivities, and quants use it to reason about how models respond to market moves.

So while Delta is written as a simple derivative, it represents a very concrete financial quantity: exposure to price moves.

1.What are finite differences?

In mathematics, a derivative measures how a quantity changes in the limit of an infinitely small move. In code, however, we never have infinitesimal changes — only finite ones.
A finite difference approximates a derivative by evaluating a function at nearby points and measuring the change.

Formally, the derivative of a function f(x)f(x)f(x) can be approximated as:

dfdx(x)  ≈  f(x+h)−f(x)h\frac{df}{dx}(x) \;\approx\; \frac{f(x + h) – f(x)}{h}

where h is a small but finite step.

Instead of asking how a function behaves at an exact point, finite differences ask a more practical question: what happens if I move the input slightly and recompute the output? This turns abstract calculus into something directly computable using repeated function evaluations.

This idea is at the heart of many numerical methods used in quantitative finance, from Greeks to PDE solvers.

Common Finite Difference Approximations

MethodFormulaAccuracyNotes
Forward differencef(x+h)−f(x)h\frac{f(x+h)-f(x)}{h}O(h)O(h)Simple, biased
Backward differencef(x)−f(x−h)h\frac{f(x)-f(x-h)}{h}O(h)O(h)Used near boundaries
Central differencef(x+h)−f(x−h)2h\frac{f(x+h)-f(x-h)}{2h}O(h2)O(h^2)Most common in practice

Here is an illustration of the 3 methods:

2.Apply Finite Differences to Greeks Calculation: The Case of Delta

Delta is defined as the derivative of an instrument’s value with respect to the underlying price. Using finite differences, this derivative can be approximated by bumping the underlying price slightly and re-pricing the instrument. Instead of relying on an analytical expression for Delta, we observe how the price changes in response to a small move in the underlying.

In practice, this means evaluating the pricing function at two nearby prices and measuring the difference:

Δ  ≈  V(S+h)−V(S−h)2h\Delta \;\approx\; \frac{V(S+h) – V(S-h)}{2h}
This central difference approximation is widely used because it is more accurate than one-sided alternatives and symmetric around the current price. It works for any pricing model and any payoff structure, which makes it especially attractive in production systems where models evolve faster than analytical formulas.

Central difference has a second-order truncation error, meaning the approximation error decreases proportionally to h2h^2as the bump size becomes smaller. In contrast, forward and backward differences only achieve first-order accuracy, with errors proportional to hhh.

This faster convergence allows central differences to reach a given accuracy with larger bump sizes, which is numerically beneficial in floating-point arithmetic. Larger bumps reduce sensitivity to rounding errors and pricing noise, making the estimate more stable in practice.

In short, central differences strike a better balance between accuracy and numerical robustness. They converge faster, are less biased, and are therefore the default choice for Delta calculations in most quantitative systems.

This calculation is usually part of a bigger picture in the Black-Scholes equation giving a theoretical price value:

3. A Practical Example to Illustrate the Calculation

Assume we are pricing a European call option and observe the following prices from our pricing function:

Underlying Price SSOption Price V(S)V(S)
99.004.52
100.005.00
101.005.49

We choose a bump size of:h=1.0h = 1.0

Using the central finite difference formula for Delta:Δ  ≈  V(S+h)−V(S−h)2h\Delta \;\approx\; \frac{V(S+h) – V(S-h)}{2h}

we plug in the observed values:Δ  ≈  5.49−4.522×1.0=0.972=0.485\Delta \;\approx\; \frac{5.49 – 4.52}{2 \times 1.0} = \frac{0.97}{2} = 0.485
A Delta of 0.485 means that, around S=100S = 100S=100, a one-unit increase in the underlying price increases the option value by approximately 0.49 units. This aligns with the intuition for a near-the-money call option, whose Delta typically lies between 0.4 and 0.6.

4. An Implementation in C++

In practice, the pricing function used to compute Delta is rarely a simple formula. It is often a reusable component shared across pricing, risk, and valuation workflows. Finite differences work particularly well in this setting because they require no changes to the pricing logic itself.

Consider a simple European call option priced using the Black–Scholes formula. We expose the pricing logic as a callable object and reuse it unchanged to compute Delta.

#include <cmath>

struct BlackScholesCall
{
    double strike;
    double rate;
    double volatility;
    double maturity;

    double operator()(double spot) const
    {
        const double sqrtT = std::sqrt(maturity);
        const double d1 =
            (std::log(spot / strike)
             + (rate + 0.5 * volatility * volatility) * maturity)
            / (volatility * sqrtT);

        const double d2 = d1 - volatility * sqrtT;

        return spot * normal_cdf(d1)
             - strike * std::exp(-rate * maturity) * normal_cdf(d2);
    }
};

The Delta computation itself remains generic:

template<typename Pricer>
double delta(Pricer&& price, double spot, double h)
{
    return (price(spot + h) - price(spot - h)) / (2.0 * h);
}

We can now compute Delta by simply bumping the spot price and reusing the same pricing function:

BlackScholesCall call{100.0, 0.01, 0.20, 1.0};

double spot = 100.0;
double bump = 0.5;

double d = delta(call, spot, bump);

5. Alternative Approaches to Calculate Delta

The appropriate method depends on the pricing model, the complexity of the payoff, and the performance requirements of the system. The table below summarises the most common approaches used in quantitative finance.

MethodHow Delta Is ObtainedAccuracyPerformanceTypical Use Cases
Analytical formulasClosed-form derivative of the pricing formulaExact (within model)Very highVanilla options, simple models
Finite differencesBump underlying and repriceApproximateMediumGeneral-purpose risk systems
PDE-based methodsLocal slope on a pricing gridApproximateHighEquity and rates models
Adjoint (AAD)Reverse differentiation of the pricerHighVery highLarge Monte Carlo portfolios

Finite differences sit at the centre of this spectrum. They are not the most accurate method, nor the fastest, but they are often the most practical. Their simplicity, model-independence, and ease of implementation make them a natural default in many production systems.

Understanding how Delta is computed — and the numerical trade-offs involved — is essential for interpreting risk numbers correctly. A Delta is not just a derivative on paper; it is the result of a numerical procedure, shaped by design choices that matter in practice.

January 2, 2026 0 comments
News

Starfighters CEO Expands Spaceport and Satellite Operations for Data Boost

by Clement D. January 1, 2026

Are investors prepared for the unexpected turbulence ahead? The day’s trading session was marked by sharp swings and heightened volatility, underscoring the pressing need for a robust risk management strategy.

In our [video: Starfighters CEO Says Looking to Add Spaceport, Aircrafts], we delve into StarFighters’ ambitious plans to scale up their low-orbit satellite operations, including the addition of a new spaceport. This could have far-reaching implications for the data center industry, a topic we’ll explore in greater depth later in the article.

Meanwhile, in [video: Mamdani Takes Reins of New York City], we witness the historic inauguration of Zohran Mamdani as the 112th mayor of New York City. This transition of power is sure to have significant ripple effects on the financial landscape of the nation’s economic hub.

Stay tuned for more updates from the [video: Today on NYSE Live | Federal Reserve Minutes Reveal Policymakers Were Split on December Rate Cut] and our [video: Mad Money 12/31/25 | Audio Only] as we navigate the day’s events and uncover the key factors shaping the market’s direction.

🎥 Starfighters CEO Says Looking to Add Spaceport, Aircrafts (Bloomberg)

In the video, Rick Svetkoff, the founder and CEO of StarFighters, discusses his company’s plans to scale up low-orbit satellite operations. He highlights the company’s efforts to add another spaceport, which could potentially support the growing demand for data centers. Svetkoff’s insights suggest that StarFighters’ initiatives could have significant market implications, particularly in the data infrastructure and satellite technology sectors.


🎥 Mamdani Takes Reins of New York City (Bloomberg)

The clip depicts Zohran Mamdani’s assumption of the office of New York City’s 112th mayor, marking the culmination of his improbable and historic rise to power over the past year. The narrative surrounding this event underscores the remarkable nature of Mamdani’s journey, as he has defied expectations and overcome significant challenges to reach this pivotal milestone in his political career.


🎥 Today on NYSE Live | Federal Reserve Minutes Reveal Policymakers Were Split on December Rate Cut (New York Stock Exchange)

In a surprising turn of events, the recently released Federal Reserve minutes have shed light on a significant divide among policymakers during the December meeting. The data reveals that officials were split on the decision to cut interest rates, with some advocating for a more dovish approach while others pushed for a more hawkish stance. This insight into the central bank’s internal deliberations provides a quantitative snapshot of the complex decision-making process that ultimately shaped the Fed’s monetary policy. Analyzing the patterns and anomalies within the minutes offers valuable clues about the factors that influenced the final outcome, potentially signaling future shifts in the Fed’s approach to managing the economy.


🎥 Mad Money 12/31/25 | Audio Only (CNBC Television)

The featured video provides an audio-only recording of Jim Cramer’s “Mad Money” program, offering viewers a personal guide through the complexities of Wall Street investing. The presentation aims to navigate the opportunities and pitfalls of the financial markets, with the primary objective of helping viewers make informed investment decisions. The content is structured around key takeaways, presented in an objective and precise manner, providing a research-oriented summary for finance enthusiasts. Viewers can access the live and exclusive video content from CNBC by subscribing to CNBC PRO, further enhancing their understanding of the evolving financial landscape.


♟️ Interested in More?

  • Read the latest financial news: c++ for quants news.
January 1, 2026 0 comments
News

2025 Trading Insights: Navigating the Markets with Cramer’s Advice

by Clement D. December 30, 2025

The Significance of Year-End Trading Dynamics: A Didactic Exploration

As the curtain falls on another eventful year in the world of finance, it is crucial for graduate students in the field to understand the nuanced dynamics that shape the final days of trading. In this structured introduction, we will delve into the key factors influencing the current market landscape, with a particular focus on the interplay between investor sentiment, macroeconomic indicators, and industry-specific trends.

To provide a comprehensive overview, we will later in the article present a series of informative videos, including “Final Days of 2025 Trading Officially Get Underway,” which offers a timely analysis of the ongoing market events, and “Mad Money 12/29/25,” a valuable audio-only resource featuring the insights of renowned financial expert Jim Cramer. Additionally, we will explore Cramer’s perspectives on the benefits of long-term investing and the criteria he recommends for stock selection, as outlined in his book “How to Make Money in Any Market.”

By delving into these diverse sources, graduate students will gain a deeper understanding of the intricate factors shaping the final trading sessions of the year, equipping them with the knowledge necessary to navigate the complex world of finance with confidence and strategic acumen.

🎥 Final Days of 2025 Trading Officially Get Underway (New York Stock Exchange)

The presentation commences with a succinct overview of the current state of the financial markets, emphasizing the pivotal juncture that marks the final days of the trading year 2025. Attendees are guided through a meticulous analysis of the key factors driving market dynamics, including the interplay of macroeconomic indicators, geopolitical developments, and investor sentiment.

The discussion then delves into the intricate mechanisms underlying the trading activities during this critical period, exploring the nuanced strategies employed by seasoned market participants. Particular attention is devoted to the complex interactions between asset classes, volatility patterns, and risk management frameworks, equipping the audience with a comprehensive understanding of the multifaceted nature of end-of-year trading.

Finally, the presentation concludes with a forward-looking perspective, highlighting the potential implications of the current market trends and their significance for the forthcoming year. Attendees are encouraged to engage in a robust Q&A session, fostering a dynamic exchange of insights and facilitating a deeper comprehension of the subject matter.


🎥 Mad Money 12/29/25 | Audio Only (CNBC Television)

The latest episode of “Mad Money” hosted by Jim Cramer offers a quantitative insight into the complex world of Wall Street investing. Analyzing patterns, anomalies, and statistical signals, Cramer navigates through the jungle of opportunities and pitfalls, providing a personal guide to help viewers make informed financial decisions. This audio-only presentation delves into the nuances of the market, empowering investors with the knowledge they need to succeed in the ever-evolving landscape of Wall Street.


🎥 Jim Cramer talks the benefits of long-term investing (CNBC Television)

In an age where the siren song of short-term gains and speculative frenzy has lured many an unwary investor, the sage counsel of veteran financial commentator Jim Cramer stands as a beacon of reason and foresight. Drawing upon his decades-long experience navigating the ebb and flow of the markets, Cramer’s treatise on the virtues of long-term investing, encapsulated in his work “How to Make Money in Any Market,” offers a timely and invaluable perspective. Amidst the cacophony of voices advocating for rapid portfolio churning and chasing the latest trends, Cramer’s measured approach serves as a reminder that the true path to sustainable wealth lies in the patient cultivation of one’s assets, weathering the storms of volatility and capitalizing on the gradual yet inexorable march of economic progress. In an era where the temptation to succumb to the allure of instant gratification is ever-present, Cramer’s insights provide a vital counterpoint, urging investors to cultivate the discipline and fortitude required to reap the bountiful rewards that long-term, prudent stewardship of one’s financial resources can yield.


🎥 Jim Cramer says you want to pick stocks that meet two criteria (CNBC Television)

The presentation opens with a discussion of the two key criteria Cramer emphasizes for successful stock selection. Firstly, the stock must exhibit strong momentum, demonstrating consistent upward price movement and robust trading volume. This momentum signals the market’s confidence in the underlying company’s prospects. Secondly, the stock should be undervalued relative to its intrinsic worth, offering investors an attractive entry point. Cramer underscores the importance of identifying this mismatch between market price and fundamental value, as it presents a lucrative opportunity for capital appreciation. He then delves into the genesis of his book “How to Make Money in Any Market,” highlighting his decades-long experience in navigating volatile market conditions and distilling his investment philosophy into a practical guide for retail investors. The presentation concludes by emphasizing Cramer’s belief that by adhering to these two principles, investors can successfully navigate the complexities of the financial markets and generate consistent returns, even in the face of prevailing economic uncertainty.


♟️ Interested in More?

  • Read the latest financial news: c++ for quants news.
December 30, 2025 0 comments
News

ETF Trends, Innovations, and Insights: A Guide to 2025 and Beyond

by Clement D. December 29, 2025

Will the AI Boom Continue? Navigating the Risks and Opportunities of the Magnificent Seven in 2026

As the AI-driven rally propels the tech titans known as the “Magnificent Seven” to soaring heights, a crucial question looms: can this extraordinary momentum be sustained in the year 2026? This analytical overview will delve into the surge of these industry behemoths, their skyrocketing valuations, and the underlying factors that may shape their future trajectory, framing the discussion in terms of risk, opportunity, and the inherent uncertainty that lies ahead.

[Reference to the video “Will the AI Boom Continue? The Fate of the Magnificent Seven in 2026”]

Additionally, this piece will explore the essential AI skills that professionals will need to stay ahead of the curve in 2026, drawing insights from the video “Essential AI Skills For 2026.” [Reference to the video]

Amidst the rapid advancements in the AI landscape, the finance world faces a crossroads, where navigating the risks and seizing the opportunities will be paramount for those seeking to thrive in the years to come.

🎥 NYSE 2025 ETF Wrap-Up: Trends, Takeaways, and What’s Next (New York Stock Exchange)

As the markets open this morning, we turn our attention to the key takeaways from the 2025 ETF Wrap-Up, a comprehensive look at the transformative year experienced by the exchange-traded fund (ETF) industry. Tim Reilly, the Head of Exchange Traded Solutions at the NYSE, joins us to provide his expert insights on the trends that shaped the market, the strategic adaptations employed by the exchange, and the promising outlook for the ETF landscape in the year ahead.

Reilly’s analysis highlights the record-breaking pace of new ETF launches, reflecting the growing investor demand for innovative products across diverse asset classes. He also delves into the shifts in investor preferences, underscoring the NYSE’s proactive approach in positioning itself to cater to these evolving needs. As we look ahead to 2026, Reilly offers a forward-looking perspective, outlining the strategies and opportunities that are poised to drive the continued expansion and adoption of ETFs in the coming year.


🎥 Trump Praises Zelenskiy After Talks With No Breakthrough (Bloomberg)

The presentation begins with an overview of the key macroeconomic factors influencing the geopolitical landscape. The discussion then transitions to an analysis of the strategic implications of the ongoing negotiations between the leaders of the United States and Ukraine. Students are encouraged to consider the potential economic ramifications of any prospective peace deal, particularly in terms of its impact on foreign direct investment, trade dynamics, and currency markets. The lecture emphasizes the importance of nuanced interpretation of diplomatic rhetoric, cautioning against overconfident extrapolation from the cordial tone of the press conference. Finally, the presentation concludes by highlighting the need for continued monitoring of the situation, as the absence of a tangible breakthrough suggests the presence of unresolved complexities that may shape future economic outcomes in the region.


🎥 Essential AI Skills For 2026 (Tina Huang)

The video “Essential AI Skills For 2026” provides a concise and analytical overview of the key skills needed to stay ahead in the rapidly evolving field of artificial intelligence. The presenter, a former data scientist at Meta, highlights the importance of mastering AI agent fundamentals, building custom AI agents, and familiarizing oneself with the latest AI language models like ChatGPT and Perplexity. The video emphasizes the market implications of these skills, suggesting that individuals who acquire them will be well-positioned to capitalize on the growing demand for AI-driven solutions across various industries. The presenter also shares valuable resources, including links to relevant tutorials and a waitlist for an upcoming AI Agent Bootcamp, further enhancing the video’s utility for viewers seeking to enhance their AI expertise.


🎥 Will the AI Boom Continue? The Fate of the Magnificent Seven in 2026 (Capital Trading)

The AI-driven rally has powered the Magnificent Seven stocks to massive gains, but can the boom continue in 2026? In this video, we examine the surge of these tech giants, rising valuations, and concerns about a potential AI bubble. We also discuss CAPE ratios, earnings growth forecasts, and whether these companies can deliver the returns investors are pricing in. The success of AI ROI could shape Wall Street’s performance for the year ahead.


♟️ Interested in More?

  • Read the latest financial news: c++ for quants news.
December 29, 2025 0 comments
top shared_ptr questions
InterviewPerformance

C++ Shared Pointers: Top shared_ptr Quant Interview Questions

by Clement D. November 30, 2025

C++ shared pointers come up again and again in quant interviews, and for good reason: they sit at the intersection of memory management, performance, ownership semantics, and real-time system reliability, all skills quants are expected to master. In modern C++ codebases used across trading desks, risk engines, and pricing libraries, std::shared_ptr is everywhere, yet many candidates only know the surface-level behavior. Interviewers use shared pointer questions to test whether you understand what’s really happening under the hood: control blocks, atomic reference counting, cache effects, and the subtle performance pitfalls that matter in low-latency environments. They also want to see if you can reason about ownership graphs, detect leaks caused by cycles, and choose correctly between shared_ptr, unique_ptr, and raw pointers in high-frequency workloads. What are the top shared_ptr questions?

Question 1: “What is a Shared Pointer? Give A Quantitative Finance Example”

A shared_ptr is a reference-counted smart pointer that enables shared ownership of a dynamically allocated object, automatically deleting it when the last owner goes away.

In many pricing engines, several components need access to the same yield-curve snapshot without copying it. A shared_ptr is ideal here because it lets each module share ownership safely. Here’s a minimal example:

#include <iostream>
#include <memory>
#include <vector>

struct YieldCurve {
    std::vector<double> tenors;
    std::vector<double> discountFactors;

    YieldCurve() {
        std::cout << "YieldCurve built\n";
    }
    ~YieldCurve() {
        std::cout << "YieldCurve destroyed\n";
    }
};

int main() {
    auto curve = std::make_shared<YieldCurve>();

    std::cout << "Ref count initially: " << curve.use_count() << "\n";

    {
        // Risk model shares the same curve
        auto riskModelCurve = curve;
        std::cout << "Ref count after risk model uses it: "
                  << curve.use_count() << "\n";
    } // riskModelCurve dies, curve stays alive

    std::cout << "Ref count after model finished: "
              << curve.use_count() << "\n";
}

What This Example Demonstrates

1. Shared Ownership of a Core Market Object

In real pricing systems, many components—pricing engines, risk calculators, scenario generators—must all access the same yield curve. Using std::shared_ptr ensures the curve persists as long as at least one module still uses it, without forcing expensive deep copies.

2. Reference Counting Behind the Scenes

Each time the shared_ptr is copied (e.g., when the risk model takes a reference), the strong reference count increases. When copies go out of scope, the count decreases. Only when the count reaches zero does the object get destroyed. This is exactly what happens to the YieldCurve instance across scopes in the example.

3. Automatic Lifetime Management (RAII)

You never call delete on the yield curve. Its lifetime is tied to the lifetime of the owning shared_ptr instances.
This reduces the classic risks in large quant codebases: dangling pointers, double deletes, and lifetime mismatches between pricing components.

Question 2: “How does shared_ptr manage reference counting?“

std::shared_ptr uses a separate control block to track how many owners an object has. Every time a shared_ptr is copied, the control block increments a strong reference count. Every time a shared_ptr is destroyed or reset, that count is decremented. When the strong count reaches zero, the managed object is automatically deleted.

Under the hood, the control block stores:

  • A strong reference count
    (number of active shared_ptr owning the object)
  • A weak reference count
    (number of weak_ptr observing the object)
  • The managed pointer
  • (Optionally) a custom deleter and allocator

All reference count updates are atomic, which makes shared_ptr safe to use across threads—though more expensive than unique_ptr. In practice, this mechanism ensures that shared market objects (like yield curves, volatility surfaces, or trade graphs) live exactly as long as the last component using them, with no need for manual delete and no risk of premature destruction. One of the top shared_ptr questions!

Question 3: “What causes a memory leak with shared_ptr?“

A memory leak with std::shared_ptr happens when two or more objects form a cyclic reference, meaning each holds a shared_ptr to the other, so their reference counts never drop to zero and their destructors never run.

For example, if struct A has std::shared_ptr<B> b; and struct B has std::shared_ptr<A> a;, creating the cycle a->b = b; and b->a = a; will leak both objects because each keeps the other alive. The fix is to use std::weak_ptr on one side of the relationship.

struct B;

struct A { std::shared_ptr<B> b; };
struct B { std::shared_ptr<A> a; }; // ← this creates a cycle and leaks

auto a = std::make_shared<A>();
auto b = std::make_shared<B>();
a->b = b;
b->a = a; // reference counts never reach 0 → leak

Here’s the same idea but fixed using std::weak_ptr so the cycle doesn’t keep the objects alive:

#include <memory>
#include <iostream>

struct B;

struct A {
    std::shared_ptr<B> b;
    ~A() { std::cout << "A destroyed\n"; }
};

struct B {
    std::weak_ptr<A> a;  // weak_ptr breaks the cycle
    ~B() { std::cout << "B destroyed\n"; }
};

int main() {
    auto a = std::make_shared<A>();
    auto b = std::make_shared<B>();

    a->b = b;
    b->a = a;  // does NOT increase refcount

    return 0;  // both A and B are destroyed normally
}
That's one of the top shared_ptr questions.

Question 4: make_shared vs. shared_ptr<T>(new T): what’s the difference?

std::make_shared<T>() and std::shared_ptr<T>(new T) both create a shared_ptr, but they differ in performance, memory layout, and exception-safety:

  • make_shared is faster and uses one allocation: it allocates the control block and the object in a single heap allocation, improving cache locality.
  • shared_ptr<T>(new T) uses two allocations: one for the control block and one for the object, making it slower and more memory hungry.
  • make_shared is exception-safe: if constructor arguments throw, no memory is leaked. With shared_ptr<T>(new T), if you add custom deleters or wrap logic incorrectly, leaks can occur.
  • make_shared is preferred except when you need a custom deleter or want separate lifetimes for control block and object (rare—e.g., weak-to-shared resurrection edge cases).

Example:

auto p1 = std::make_shared<MyObject>();        // one allocation, safe
auto p2 = std::shared_ptr<MyObject>(new MyObject());  // two allocations

Question 5: Why is shared_ptr slower?

std::shared_ptr is slower because it performs atomic reference counting, extra bookkeeping, and sometimes extra allocations to manage shared ownership. Every copy of a shared_ptr must atomically increment the control block’s reference count, and every destruction must atomically decrement it; these atomic operations create contention, inhibit compiler optimizations, and add CPU overhead. A shared_ptr also maintains both a strong and weak count, uses a control block to track them, and may require separate heap allocations (unless created via make_shared). This combination of atomic ops + bookkeeping + heap activity makes shared_ptr significantly slower than a raw pointer or even a unique_ptr, which performs no reference counting at all.

November 30, 2025 0 comments
C++ Clang Formatter
IDELibraries

Clang Formatting for C++: An Overview of Clang-Format

by Clement D. November 23, 2025

Maintaining consistent C++ style across a large codebase is one of the simplest ways to improve readability, reduce onboarding time, and prevent unnecessary merge conflicts. Yet many C++ teams, especially in quantitative finance, where codebases grow organically over years still rely on manual style conventions or developer-specific habits. The result is familiar: inconsistent indentation, mixed brace styles, scattered spacing rules, and code that “looks” different depending on who touched it last. Clang-Format solves this problem. What is Clang formatting for C++?

Part of the Clang and LLVM ecosystem, clang-format is a fast, deterministic, fully automated C++ formatter that rewrites your source code according to a predefined set of style rules. Instead of arguing about formatting in code reviews or spending time manually cleaning up diffs, quant developers can enforce a single standard across an entire pricing or risk library automatically and reproducibly.

1.What is the Clang and LLVM ecosystem?

The Clang and LLVM ecosystem is a modern, modular compiler toolchain used for building, analyzing, and optimizing C++ (and other language) programs. Clang is the front-end: it parses C++ code, checks syntax and types, produces highly readable diagnostics, and generates LLVM’s intermediate representation (IR). LLVM is the backend: a collection of reusable compiler components that optimize the IR and generate machine code for many architectures (x86-64, ARM, etc.). Unlike monolithic compilers like GCC, the Clang/LLVM stack is built as independent libraries, which makes it incredibly flexible.

This design allows developers to build tools such as clang-format, clang-tidy, source-to-source refactoring engines, static analyzers, and custom compiler plugins. The ecosystem powers modern IDE features, code intelligence, and even JIT-compiled systems.

Because of its modularity, fast compilation, modern C++ standard support, and rich tooling, Clang/LLVM has become the backbone of many large C++ codebases, including those used in finance, gaming, scientific computing, and operating systems like macOS.

2.Clang-Format: The Modern Standard for C++ Code Formatting

Clang-format has become the default choice for formatting C++ code across many industries, from finance to large-scale open-source projects. Built on top of the Clang and LLVM ecosystem, it provides a fast, deterministic, and fully automated way to enforce consistent style rules across an entire codebase.

Instead of relying on ad-hoc conventions or individual preferences, teams can define a single .clang-format configuration and apply it uniformly through editors, CI pipelines, and pre-commit hooks. The result is cleaner diffs, fewer formatting discussions in code reviews, and a more maintainable codebase—crucial benefits for large C++ systems such as pricing engines, risk libraries, or high-performance trading infrastructure.

3.Installation

How to start using Clang formatting for C++? Let’s start with installation.

I’m using mac, and it’s as simple as:

➜  ~ brew install clang-format

==> Fetching downloads for: clang-format
✔︎ Bottle Manifest clang-format (21.1.6)            [Downloaded   12.7KB/ 12.7KB]
✔︎ Bottle clang-format (21.1.6)                     [Downloaded    1.4MB/  1.4MB]
==> Pouring clang-format--21.1.6.sonoma.bottle.tar.gz
🍺  /usr/local/Cellar/clang-format/21.1.6: 11 files, 3.4MB
==> Running `brew cleanup clang-format`...

With linux, it would also be as simple as:

➜  ~ sudo apt-get install clang-format

To get a general overview of the tool, just run the –help command:

➜  ~ clang-format --help

OVERVIEW: A tool to format C/C++/Java/JavaScript/JSON/Objective-C/Protobuf/C# code.

If no arguments are specified, it formats the code from standard input
and writes the result to the standard output.
If <file>s are given, it reformats the files. If -i is specified
together with <file>s, the files are edited in-place. Otherwise, the
result is written to the standard output.

USAGE: clang-format [options] [@<file>] [<file> ...]

OPTIONS:

Clang-format options:

  --Werror                       - If set, changes formatting warnings to errors
  --Wno-error=<value>            - If set, don't error out on the specified warning type.
    =unknown                     -   If set, unknown format options are only warned about.
                                     This can be used to enable formatting, even if the
                                     configuration contains unknown (newer) options.
                                     Use with caution, as this might lead to dramatically
                                     differing format depending on an option being
                                     supported or not.
  --assume-filename=<string>     - Set filename used to determine the language and to find
                                   .clang-format file.
                                   Only used when reading from stdin.
                                   If this is not passed, the .clang-format file is searched
                                   relative to the current working directory when reading stdin.
                                   Unrecognized filenames are treated as C++.
                                   supported:
                                     CSharp: .cs
                                     Java: .java
                                     JavaScript: .js .mjs .cjs .ts
                                     Json: .json .ipynb
                                     Objective-C: .m .mm
                                     Proto: .proto .protodevel
                                     TableGen: .td
                                     TextProto: .txtpb .textpb .pb.txt .textproto .asciipb
                                     Verilog: .sv .svh .v .vh
  --cursor=<uint>                - The position of the cursor when invoking
                                   clang-format from an editor integration
  --dry-run                      - If set, do not actually make the formatting changes
  --dump-config                  - Dump configuration options to stdout and exit.
                                   Can be used with -style option.
  --fail-on-incomplete-format    - If set, fail with exit code 1 on incomplete format.
  --fallback-style=<string>      - The name of the predefined style used as a
                                   fallback in case clang-format is invoked with
                                   -style=file, but can not find the .clang-format
                                   file to use. Defaults to 'LLVM'.
                                   Use -fallback-style=none to skip formatting.
  --ferror-limit=<uint>          - Set the maximum number of clang-format errors to emit
                                   before stopping (0 = no limit).
                                   Used only with --dry-run or -n
  --files=<filename>             - A file containing a list of files to process, one per line.
  -i                             - Inplace edit <file>s, if specified.
  --length=<uint>                - Format a range of this length (in bytes).
                                   Multiple ranges can be formatted by specifying
                                   several -offset and -length pairs.
                                   When only a single -offset is specified without
                                   -length, clang-format will format up to the end
                                   of the file.
                                   Can only be used with one input file.
  --lines=<string>               - <start line>:<end line> - format a range of
                                   lines (both 1-based).
                                   Multiple ranges can be formatted by specifying
                                   several -lines arguments.
                                   Can't be used with -offset and -length.
                                   Can only be used with one input file.
  -n                             - Alias for --dry-run
  --offset=<uint>                - Format a range starting at this byte offset.
                                   Multiple ranges can be formatted by specifying
                                   several -offset and -length pairs.
                                   Can only be used with one input file.
  --output-replacements-xml      - Output replacements as XML.
  --qualifier-alignment=<string> - If set, overrides the qualifier alignment style
                                   determined by the QualifierAlignment style flag
  --sort-includes                - If set, overrides the include sorting behavior
                                   determined by the SortIncludes style flag
  --style=<string>               - Set coding style. <string> can be:
                                   1. A preset: LLVM, GNU, Google, Chromium, Microsoft,
                                      Mozilla, WebKit.
                                   2. 'file' to load style configuration from a
                                      .clang-format file in one of the parent directories
                                      of the source file (for stdin, see --assume-filename).
                                      If no .clang-format file is found, falls back to
                                      --fallback-style.
                                      --style=file is the default.
                                   3. 'file:<format_file_path>' to explicitly specify
                                      the configuration file.
                                   4. "{key: value, ...}" to set specific parameters, e.g.:
                                      --style="{BasedOnStyle: llvm, IndentWidth: 8}"
  --verbose                      - If set, shows the list of processed files

Generic Options:

  --help                         - Display available options (--help-hidden for more)
  --help-list                    - Display list of available options (--help-list-hidden for more)
  --version                      - Display the version of this program

4.Usage

Imagine a messy piece of C++ code calculating DVA with formatting problems all over:

#include <iostream>
 #include<vector>
#include <cmath>

double computeDVA(const std::vector<double>& exposure,
 const std::vector<double>& pd,
   const std::vector<double> lgd, double discount)
{
double dva=0.0;
for (size_t i=0;i<exposure.size();i++){
double term= exposure[i] * pd[i] * lgd[i] *discount;
   dva+=term;
}
 return dva; }

int   main() {

std::vector<double> exposure = {100,200,150,120};
 std::vector<double> pd={0.01,0.015,0.02,0.03};
  std::vector<double> lgd = {0.6,0.6,0.6,0.6};
double discount =0.97;

double dva = computeDVA(exposure,pd,lgd,discount);

 std::cout<<"DVA: "<<dva<<std::endl;

return 0;}

This respects the general DVA formula (from the XVA family):

Let’s format it with clang-format using the LLVM style, I run:

clang-format -i -style=LLVM dva.cpp

with:

-i = overwrite the file in place
-style=LLVM = apply the LLVM formatting style

It becomes sweet and nice:

#include <cmath>
#include <iostream>
#include <vector>

double computeDVA(const std::vector<double> &exposure,
                  const std::vector<double> &pd, const std::vector<double> lgd,
                  double discount) {
  double dva = 0.0;
  for (size_t i = 0; i < exposure.size(); i++) {
    double term = exposure[i] * pd[i] * lgd[i] * discount;
    dva += term;
  }
  return dva;
}

int main() {

  std::vector<double> exposure = {100, 200, 150, 120};
  std::vector<double> pd = {0.01, 0.015, 0.02, 0.03};
  std::vector<double> lgd = {0.6, 0.6, 0.6, 0.6};
  double discount = 0.97;

  double dva = computeDVA(exposure, pd, lgd, discount);

  std::cout << "DVA: " << dva << std::endl;

  return 0;
}

5. A List and Comparison of The Clang Styles

Formatting styles in clang-format come from real, large-scale C++ codebases: LLVM, Google, Chromium, Mozilla, and others. Each style reflects the conventions of the organization that created it, and each emphasizes different priorities such as readability, compactness, or strict consistency. While clang-format supports many styles, they all serve the same purpose: enforcing a predictable, automated layout for C++ code across complex projects. Here is an overview of Clang formatting for C++ via a list of styles available:

StyleOrigin / Used ByBrace StyleIndentationLine LengthNotable Traits
LLVMLLVM/Clang projectStroustrup-like2 spaces80Clean, minimal, modern; default for clang-format
GoogleGoogle C++ Style GuideAllman/Google2 spaces80Very consistent; strong whitespace rules
ChromiumChromium/Google ChromeK&R2 spaces80Optimized for very large codebases
MozillaFirefoxAllman2 or 4 spaces99Slightly looser than Google; readable
WebKitWebKit / SafariStroustrup4 spaces120Widely spaced; readable for UI and engine code
GNUGNU coding standardGNU style2 spaces79Uncommon now; unusual brace placements
MicrosoftMicrosoft C++/C#Allman4 spaces120Familiar to Windows devs; wide spacing
JSJavaScript projectsK&R2 spaces80For JS/TS/CSS formatting, not C++
FileCustom .clang-format———User-defined rules; highly flexible

Among all available clang-format styles, LLVM stands closest to a true industry standard for modern C++ development. Its clean, neutral layout makes it easy to read, easy to maintain, and suitable for teams of any size: from open-source contributors to quant developers in large financial institutions. Unlike more opinionated styles such as Google or GNU, LLVM avoids strong stylistic constraints and focuses instead on clarity and consistency.

This neutrality is exactly why so many projects adopt it as their base style or use it directly without modification. For quant teams working on pricing engines, risk libraries, or low-latency infrastructure, LLVM offers a stable, widely trusted foundation that integrates seamlessly into automated workflows and CI pipelines.

If you need a formatting standard that “just works” across diverse C++ codebases, LLVM is the safest and most broadly compatible choice.

6. Manage Clang Formating in your Codebase

he easiest way to standardize formatting across an entire C++ codebase is to create a .clang-format file at the root of your project. This file acts as the single source of truth for your formatting rules, ensuring every developer, editor, and CI job applies exactly the same style. Once the file is in place, running clang-format becomes fully deterministic: every file in your project will follow the same indentation, spacing, brace placement, and wrapping rules.

A .clang-format file can be as simple as one line—BasedOnStyle: LLVM—or it can define dozens of customized options tailored to your team. Developers don’t need to memorize or manually enforce formatting conventions; the file encodes all rules, and clang-format applies them automatically. Most editors (VSCode, CLion, Vim, Emacs) pick up the configuration instantly, and CI pipelines can run clang-format checks to prevent unformatted code from entering the repository.

An example of .clang-format file:

BasedOnStyle: LLVM

# Indentation & Alignment
IndentWidth: 2
TabWidth: 2
UseTab: Never

# Line Breaking & Wrapping
ColumnLimit: 100
AllowShortIfStatementsOnASingleLine: false
AllowShortFunctionsOnASingleLine: Empty

# Braces & Layout
BreakBeforeBraces: LLVM
BraceWrapping:
  AfterNamespace: false
  AfterClass: false
  AfterControlStatement: false

# Includes
IncludeBlocks: Regroup
SortIncludes: true

# Spacing
SpaceBeforeParens: ControlStatements
SpacesInParentheses: false
SpaceAfterCStyleCast: true

# C++ Specific
Standard: Latest
DerivePointerAlignment: false
PointerAlignment: Left

# Comments
ReflowComments: true

# File Types
DisableFormat: false

Put your file inside your project directory, example of structure:

my-project/
  .clang-format
  src/
    dva.cpp
    pricer.cpp

Once the .clang-format file is in place:

  • No need to specify -style
  • No need to pass config flags
  • clang-format automatically uses your project’s style rules

Just run:

clang-format -i myfile.cpp

And your team stays fully consistent.

7. Include clang-format in. a pre-commit hook

You might want to do more than that: automate the formatting when commiting to GIT.
For this, create a pre-commit hook file:

.git/hooks/pre-commit

Make it executable:

chmod +x .git/hooks/pre-commit

Paste this script inside:

#!/bin/bash

# Format only staged C++ files
files=$(git diff --cached --name-only --diff-filter=ACM | grep -E "\.(cpp|hpp|cc|hh|c|h)$")

if [ -z "$files" ]; then
    exit 0
fi

echo "Running clang-format on staged C++ files..."

for file in $files; do
    clang-format -i "$file"
    git add "$file"
done

echo "Clang-format applied."

What it does:

  • Detects staged C++ files only
  • Runs clang-format using your .clang-format rules
  • Re-adds the formatted files to the commit
  • Prevents style drift or “format fixes” later
  • Completely automatic

This means a developer cannot commit unformatted C++ code.

November 23, 2025 0 comments
  • 1
  • 2
  • 3
  • …
  • 8

@2025 - All Right Reserved.


Back To Top
  • Home
  • News
  • Contact
  • About