<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Fabio Di Giovanni on Medium]]></title>
        <description><![CDATA[Stories by Fabio Di Giovanni on Medium]]></description>
        <link>https://medium.com/@fabiodigiovanni97?source=rss-44319ea4bb38------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TPZIDNnyLw8EbGkq36T1kg.png</url>
            <title>Stories by Fabio Di Giovanni on Medium</title>
            <link>https://medium.com/@fabiodigiovanni97?source=rss-44319ea4bb38------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 01:00:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fabiodigiovanni97/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Verify an Equity Forward Price (in 5 Minutes)]]></title>
            <link>https://medium.com/@fabiodigiovanni97/how-to-verify-an-equity-forward-price-in-5-minutes-da11f979dd4d?source=rss-44319ea4bb38------2</link>
            <guid isPermaLink="false">https://medium.com/p/da11f979dd4d</guid>
            <category><![CDATA[pricing-strategy]]></category>
            <category><![CDATA[credit-risk]]></category>
            <category><![CDATA[risk-management]]></category>
            <category><![CDATA[derivatives]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[Fabio Di Giovanni]]></dc:creator>
            <pubDate>Mon, 09 Feb 2026 06:33:32 GMT</pubDate>
            <atom:updated>2026-02-09T06:33:32.543Z</atom:updated>
            <content:encoded><![CDATA[<h4>Two independent checks (carry + put–call parity), a PASS/FAIL rule, and a break-investigation checklist (plus a Python mini-tool).</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2kGtWhtUP-8GYnrs4eIA1Q.png" /></figure><blockquote>If two independent methods don’t agree, the issue is usually not the math — it’s the inputs.</blockquote><p>In Valuation Control / IPV, the objective is not to reinvent pricing models. The objective is to <strong>independently verify</strong> a desk valuation with <strong>robust, explainable checks</strong> and a clear break-investigation path.</p><p>This playbook shows a simple framework for <strong>equity forwards</strong> using two independent approaches:</p><ol><li>a <strong>carry-based forward</strong> (rates + dividends/carry)</li><li>a <strong>forward implied from options</strong> via <strong>put–call parity</strong></li></ol><p>If both checks agree within tolerance, you have a strong baseline. If not, you have a structured way to diagnose why.</p><h3>1. 📌 <strong>Instrument</strong></h3><p>An <strong>equity forward</strong> is an agreement to buy (or sell) an equity at a future date <strong><em>T</em></strong> for a price fixed today (the forward price).<br> At maturity, a <strong>long</strong> equity forward delivers a linear payoff: you benefit if the stock ends above the strike and lose if it ends below.</p><p><strong>Payoff at maturity:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yhVeBEaVLTpuiFX2MfxF3Q.png" /></figure><p>Where:</p><ul><li><strong><em>Sᴛ</em></strong><em>​</em> = equity price at maturity</li><li><strong><em>K</em></strong> = forward strike</li></ul><h3>2. 🧾 <strong>Inputs</strong></h3><p>To run a practical IPV check, you need a small, well-defined set of inputs.</p><h4>Market inputs</h4><ul><li>Spot price <strong><em>S₀</em></strong> (<strong>timestamped)</strong></li><li>Discount rate <strong><em>r</em></strong> (consistent with the pricing convention used for the option quotes)</li><li>Dividend/carry assumption <strong><em>q</em></strong> (dividend yield or an equivalent carry input)</li><li>Maturity <strong><em>T</em></strong> as a year fraction (day count matters)</li><li>Strike <strong><em>K</em></strong></li></ul><blockquote><strong>Note:</strong> Ensure the compounding convention (continuous vs simple/annual) of the rate <strong>r</strong> matches the one used in the formula. In this PoC, we assume continuous compounding.</blockquote><h4>Options inputs (for the parity check)</h4><ul><li>Call price <strong><em>C(K,T)</em></strong></li><li>Put price <strong><em>P(K,T)</em></strong></li></ul><blockquote><strong>Important control note:</strong> the call and put must be on the <strong>same underlying</strong>, with the <strong>same strike K</strong> and <strong>same maturity T</strong> (and ideally aligned timestamps and settlement conventions).</blockquote><h3>3. 🧮 Baseline Valuation<strong>: Carry-based forward</strong></h3><p>The carry model gives a clean baseline forward level:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*EWX-uOOVxLLJVAnmn9mJEw.png" /></figure><p>This is not about being “perfect”. It’s about having a <strong>stable reference</strong> that you can recompute independently with a small set of transparent inputs.</p><h4>Practical interpretation</h4><ul><li><strong><em>r</em></strong> pushes the forward <strong>up</strong> (you can earn interest on cash until maturity)</li><li><strong><em>q</em></strong> pushes the forward <strong>down</strong> (dividends reduce the effective growth of the spot)</li><li>Differences between teams often come from how <strong>dividends/carry</strong> are represented (yield vs discrete dividends) and from <strong>conventions</strong> (compounding and day count)</li></ul><blockquote><strong>Note: </strong>While we use a continuous yield <strong>q</strong> for simplicity in this playbook, in a production IPV environment for single stocks, you would typically use a <strong>discrete dividend schedule</strong> (actual cash amounts and ex-dates). Furthermore, <strong>q</strong> is often treated as <strong>“Net Carry”</strong> — meaning the dividend yield is adjusted for <strong>stock borrowing costs (repo)</strong>. On “hard-to-borrow” names, the repo effect can be significant enough to outweigh the dividend yield itself, moving the forward price materially.</blockquote><p>As a first-line IPV check, this baseline is hard to beat: it’s simple, explainable, and fast.</p><h3>4. 🧩 <strong>Check #2: Options-implied forward (put–call parity)</strong></h3><p>A forward can also be inferred from option prices. The core idea: a <strong>long call and short put</strong> (same <strong><em>K, T</em></strong>) behaves like a forward at maturity.</p><p>Put–call parity (same <strong><em>K, T</em></strong>, European-style framework):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*T58YS6_Zv8v5OUGw0rItuQ.png" /></figure><blockquote><strong>Note:</strong> This relationship holds strictly for European options. For American-style equity options (common in single stocks), the possibility of early exercise — especially when dividends are high — turns the parity into a set of inequalities or requires an American pricing engine to extract the implied forward.</blockquote><p>Rearranging gives a forward implied by options:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*QLNlQuEQ8DqJLZTdVFZG2g.png" /></figure><p>In practice, breaks most often come from dividend assumptions, timestamp mismatches, or conventions — not from the parity itself.</p><h4>Why this is useful in control</h4><ul><li>It is <strong>market-implied</strong>: it comes directly from liquid option quotes (when available)</li><li>It gives you an <strong>independent cross-check</strong> that often detects issues in rates/dividends assumptions, quote alignment, or mapping errors</li></ul><h4>Visual intuition (payoff replication)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*tFJsSkJ4N9-TWHZR7ECv1A.png" /></figure><p><strong>At maturity:</strong></p><ul><li>The <strong>long call</strong> pays max⁡(<em>Sᴛ−K</em>,0)</li><li>The <strong>short put</strong> pays −max⁡(<em>K−Sᴛ</em>,0)</li><li>Adding them gives a <strong>synthetic long forward</strong>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*yfPgj0ANsxRUHd3FqyJLng.png" /></figure><p>i.e., a straight line with slope 1 crossing zero at <em>Sᴛ = K</em>.</p><h3>5. ✅ <strong>Decision rule (PASS/FAIL)</strong></h3><h4><strong>Tolerance: practical guidance</strong></h4><p>In real markets, you should not expect <strong>Δ<em>F = 0</em></strong> exactly. Your tolerance should reflect:</p><ul><li>bid/ask spreads and liquidity</li><li>timestamp alignment (spot vs options)</li><li>mid vs executable side</li><li>convention mismatches (day count, compounding, curve)</li></ul><h4><strong>A pragmatic control rule</strong></h4><p>Instead of choosing either an absolute tolerance or a bps tolerance, you can combine both with a single effective threshold:</p><ul><li>absolute tolerance (currency units), and</li><li>relative tolerance (bps)</li></ul><p>Define:</p><ul><li>Δ<em>F</em> = F_parity−F_carry</li><li>an <strong>effective tolerance</strong>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*FDO77ig1H-d3nqdkUdt6Ig.png" /></figure><p><strong>PASS/FAIL rule</strong></p><ul><li><strong>PASS</strong> if ∣Δ<em>F</em>∣≤tol_eff</li><li><strong>FAIL</strong> otherwise</li></ul><h3>6. 📊 <strong>IPV output (mini-report)</strong></h3><p>A simple, repeatable output is often more valuable than a complex model. The goal is to produce a “control view” that you can paste into a ticket, share with stakeholders, and re-run consistently across instruments.</p><p>The report should show the two forward levels side by side: the carry-based baseline forward F_carry and the options-implied forward F_parity. Then it should quantify the difference Δ<em>F </em>= F_parity−F_carry​ both in absolute currency terms and in basis points. In practice, it is helpful to express bps in two ways: bps versus the baseline forward (a natural control normalization) and bps versus spot (useful when comparing the magnitude of breaks across underlyings with different forward levels).</p><p>Most importantly, the report should make the decision rule explicit. In this playbook, we use a single effective tolerance tol_eff​ that combines an absolute threshold and a bps threshold, and we flag FAIL when ∣Δ<em>F</em>∣ exceeds tol_eff​​. This prevents ambiguity and makes the outcome auditable.</p><p>Finally, a good IPV report is diagnostic, not just a red/green flag. That’s why the output also includes a net carry check: the input net carry q_input​, the implied net carry q_impl required to reconcile the carry model with the market-implied forward, and the net carry gap Δ<em>q</em> in bps. When Δ<em>q</em> is large, it’s often the fastest signal that the break is driven by dividends or borrow/repo assumptions rather than “math”.</p><h3>7. 🕵️ Break investigation checklist</h3><p>If <strong>∣Δ<em>F</em>∣</strong><em> </em>is outside tolerance, the key is to investigate in a structured order. The goal is to turn a “mysterious discrepancy” into a small set of concrete hypotheses that you can test quickly.</p><p>Start with data synchronization. Check that spot and option quotes are aligned to the same “as-of” time, and confirm whether you are using mid quotes or executable sides consistently. Timestamp mismatches and stale quotes are among the most common causes of apparent breaks.</p><p>Then move to corporate actions and carry. Verify that dividends are handled consistently, including discrete dividends, specials, splits, and other corporate actions. If your report shows a material Δ<em>q</em>, treat it as a strong hint to focus immediately on the dividend schedule and on borrow/repo assumptions, especially for hard-to-borrow names where financing effects can dominate.</p><p>Next, confirm conventions. Re-check the maturity year fraction <strong><em>T</em></strong>, the day count, and the compounding convention used for rates and carry. Small convention mismatches are enough to generate systematic discrepancies, especially when teams use different curve building or day count assumptions.</p><p>After that, validate the yield curve and discounting setup. Ensure the discount rate <strong><em>r</em></strong> is consistent with the market quotes you are using and with the internal pricing convention (for example, whether the desk uses OIS, IBOR, or an internal funding curve). Misalignment here can create breaks even when everything else looks correct.</p><p>Finally, check option style and mapping. Put–call parity holds strictly for European options; for American-style equity options, early exercise — especially around dividends — can invalidate an equality-based check. Also confirm that the call and put are on the same underlying, with the same strike and maturity, and that settlement conventions match. These mapping issues are surprisingly common and often explain “mystery” breaks in production.</p><h3>8. 💻 <strong>Python </strong>Proof of Concept (PoC) Tool</h3><p>Below is a compact Python workflow that turns this playbook into an executable IPV check. Unlike a simple pricing calculator, this script includes a <strong>Net Carry diagnostic</strong> function — essential for identifying the “root cause” immediately when a check fails.</p><h4>Core Logic: Baseline vs. Market Implied</h4><p>The tool computes a carry-based baseline forward and a parity-implied forward from option quotes. It then applies a clear PASS/FAIL rule based on a single effective tolerance</p><p>If the check fails, the tool computes:</p><ul><li>the <strong>implied net carry</strong> q_impl​ required to reconcile the carry model with the market-implied forward, and</li><li>the <strong>net carry gap</strong> Δ<em>q</em> in bps, a strong “root cause signal” for dividends/repo/borrow assumptions.</li></ul><p>The output is intentionally “desk-style”: short, explicit, and diagnostic.</p><pre>tol_eff = max(tol_abs, abs(tol_bps) * f_baseline / 10000.0)<br>status = &quot;PASS&quot; if abs(abs_spread) &lt;= tol_eff else &quot;FAIL&quot;<br><br>q_impl = implied_net_carry(spot, f_mkt, r, T)<br>q_gap_bps = None if q_impl is None else (q_impl - net_carry) * 10000.0</pre><h4>Example Output: The IPV Report</h4><p>When running the check on a scenario with a discrepancy (e.g., a dividend mismatch), the tool produces a professional-grade report:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nY6m0MLmi_edmwITD4XcWg.png" /></figure><h3>How to interpret this result (and what to do next)</h3><p>This report doesn’t just flag a FAIL — it points you toward the most likely driver.</p><ul><li><strong>Rule transparency:</strong> the report shows the exact pass criterion <br>(<strong>∣Δ<em>F</em>∣ ≤ </strong>tol_eff). No ambiguity.</li><li><strong>Magnitude:</strong> <strong>Δ<em>F</em> = −0.599</strong> is far outside tolerance (tol_eff<strong> ​= 0.200</strong>). This is not rounding noise — it’s an input/alignment issue.</li><li><strong>Direction:</strong> F_parity&lt; F_carry​ means the market is implying <strong>more negative carry</strong> than your baseline (e.g., higher dividends, higher borrow/repo costs, or spot/options not aligned in time).</li><li><strong>Net carry signal:</strong> the tool estimates q_impl = 2.190% vs q_input = 1.0%, so Δ<em>q</em> = +119 bps. That’s a strong diagnostic flag: investigate dividends and borrow/repo first, then check quote staleness and conventions.</li></ul><p>In Valuation Control, a good FAIL is often more valuable than a PASS: it demonstrates the control framework is sensitive to real-world data issues and provides a structured path to resolution.</p><h3>9. 🧾 <strong>Conclusion</strong></h3><p>This playbook demonstrates that effectiveness in valuation control doesn’t require excessive complexity — it requires a workflow that is <strong>independent, explainable, and repeatable</strong>. For an equity forward, the dual-check framework (Baseline Carry vs. Options-Implied) provides exactly that: a clear baseline and a market-driven cross-check.</p><p>Most importantly, this approach shifts the mindset from “checking a box” to “analyzing the market”. When results diverge, the focus isn’t on proving the model wrong, but on identifying which assumption — dividends, repo rates, or settlement conventions — is driving the difference. By using the provided Python PoC, you can turn a “mysterious discrepancy” into a structured, testable hypothesis.</p><p>In a professional IPV environment, this level of transparency is what builds trust in the bank’s valuation books. Whether you are building a library of control checks or preparing for a desk review, the principle remains the same: <strong>start simple, make it robust, and automate the diagnostics.</strong></p><blockquote><em>📥 </em><strong><em>Explore the full implementation</em></strong><em> on GitHub → </em><a href="https://github.com/fabiodigiovanni/equity-forward-ipv-check"><em>https://github.com/fabiodigiovanni/equity-forward-ipv-check</em></a></blockquote><h3>Let’s Connect!</h3><p>If you work in IPV / Valuation Control, I’d love to exchange notes — feel free to connect on <a href="https://www.linkedin.com/in/fabio-di-giovanni/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da11f979dd4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From PD to Pareto: Turning Credit Risk Models into Efficient Portfolio Decisions]]></title>
            <link>https://medium.com/@fabiodigiovanni97/from-pd-to-pareto-turning-credit-risk-models-into-efficient-portfolio-decisions-0b1ac3f3a5d2?source=rss-44319ea4bb38------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b1ac3f3a5d2</guid>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[risk-management]]></category>
            <category><![CDATA[model]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[credit-risk-modelling]]></category>
            <dc:creator><![CDATA[Fabio Di Giovanni]]></dc:creator>
            <pubDate>Tue, 09 Dec 2025 08:10:12 GMT</pubDate>
            <atom:updated>2025-12-09T08:10:12.279Z</atom:updated>
            <content:encoded><![CDATA[<h4>How multi-objective optimization, Pareto frontiers, and a simple Python demo help you balance return, expected loss, and capital in credit portfolios.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*usybEYlFsqbyhqmO6Gqqyg.png" /></figure><p>Imagine you’re managing a consumer loan portfolio across four countries.</p><p>Your mandate for next year looks like this:</p><ul><li>grow the book by +8–10%</li><li>keep expected loss below 2%</li><li>stay within a tight capital budget</li><li>respect concentration limits by country and risk band</li></ul><p>You have good models: PD/LGD/EAD, IFRS 9 staging, stress tests.<br> But the real question is:</p><blockquote><strong><em>How do you turn all those risk parameters into actual allocation decisions under multiple, conflicting objectives?</em></strong></blockquote><p>In this article I’ll argue that the most realistic way to think about the problem is <em>not</em> “maximize one metric”, but:</p><blockquote><strong><em>View portfolio decisions as choosing a point on a Pareto frontier — a set of efficient trade-offs between return, risk and capital.</em></strong></blockquote><p>Under the hood, Linear Programming (LP) and its relatives act as engines that compute these efficient points.</p><p>In the second half of the article I build a small synthetic portfolio, solve a realistic LP in Python, and plot an efficient frontier in expected-loss–return space under capital and concentration constraints.</p><h3>1. A Concrete Credit Portfolio Problem 🧩</h3><p>Let’s make the setting explicit.</p><p>You manage a retail credit portfolio split into segments by <strong>country</strong> and <strong>risk band</strong> (based on PD). For each segment <em>i,</em> you know:</p><ul><li>expected return per unit exposure: r_i</li><li>probability of default: PD_i</li><li>loss given default: LGD_i</li><li>regulatory risk weight: α_i</li></ul><p>You control the exposure x_i in each segment. These x_i are your <strong>decision variables</strong>.</p><p>Your management and Risk Appetite Statement implicitly imposes multiple objectives:</p><ul><li>grow <strong>expected return</strong>,</li><li>keep <strong>expected loss</strong> and <strong>capital usage</strong> under control,</li><li>keep <strong>concentration</strong> within limits,</li><li>avoid excessive <strong>volatility</strong> of losses in stress.</li></ul><p>This is clearly not a single “maximize profit” problem — it is a <strong>multi-objective</strong> one.</p><h3>2. Multi-Objective Optimization and Pareto 🎯</h3><p>In a standard constrained optimization problem you minimize a <strong>single</strong> objective f(x) subject to constraints:</p><ul><li>x = vector of decisions (exposures, approval flags, limits, etc.)</li><li>f(x) = objective (e.g. negative profit, a risk measure, a cost)</li><li>constraints encode capital, budget, concentration, regulation, and so on</li></ul><p>In a credit portfolio, we typically care about <strong>several</strong> objectives at the same time. A natural choice is:</p><ul><li>f1(x) = -R(x) → negative expected return (we want to minimize it)</li><li>f2(x) = EL(x) → expected loss</li><li>f3(x) = K(x) → capital usage</li></ul><p>You can’t usually find a single x that simultaneously minimizes all components. This is where <strong>Pareto optimality</strong> enters.</p><p>A portfolio x(1) <strong>dominates</strong> another portfolio x(2) if it is at least as good on every objective, and strictly better on at least one. A portfolio is <strong>Pareto efficient</strong> if there is no other feasible portfolio that dominates it.</p><p>The set of all Pareto-efficient portfolios is the <strong>Pareto frontier</strong> (or efficient frontier). Intuitively:</p><blockquote><em>On the frontier you can’t improve any objective (e.g. increase return or reduce EL) without worsening at least one other.<br> Below the frontier you are leaving money on the table.</em></blockquote><p>A tiny numerical example makes this concrete. Suppose you have four portfolios:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*n9YeL6RCZ0g0dr8DkmmEVA.png" /></figure><p>We like higher return and lower EL/capital.</p><ul><li>B and C do not dominate each other: B has more return but also more EL and capital. That’s a genuine trade-off.</li><li>D <strong>dominates</strong> A: same return, same EL, but less capital. There is no reason to choose A.</li></ul><p>A risk manager will not always pick the highest-return or lowest-risk portfolio, but should at least avoid <strong>dominated</strong> ones. The efficient frontier is the set of non-dominated portfolios.</p><h3>3. From PD/LGD/EAD to Portfolio Objectives 🧮</h3><h4>Back to our credit portfolio.</h4><p>For each segment <em>i</em> we know:</p><ul><li>PD_i, LGD_i, EAD_i (if needed)</li><li>x_i: exposure (decision variable)</li><li>r_i: expected return per unit exposure</li><li>α_i: risk weight proxy for capital</li></ul><p>We can define:</p><ul><li><strong>Expected return:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*6xUVGxUV1Q5BANTBY2EK-A.png" /></figure><ul><li><strong>Expected loss:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*3MRJDFGHiihJ3Lb2imkXuQ.png" /></figure><ul><li><strong>Capital usage / RWA proxy:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*hoNFQAoEQ8wPf5O7xF4sYw.png" /></figure><p>In words: portfolio expected return is just the returns of each segment weighted by its exposure; expected loss is PD × LGD × exposure summed across segments; and capital is a risk-weighted sum of exposures.</p><p>If we also care about portfolio-level volatility or correlations, we can introduce a covariance matrix Σ of segment-level losses and define a risk measure like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*aMo3ABnUJjvgP5oXYYdQAw.png" /></figure><p>A very natural <strong>multi-objective</strong> problem is then:</p><blockquote><em>Minimize </em><em>(-R(x), EL(x), K(x))<br> subject to: </em><strong><em>“exposure budget”</em></strong>, <strong><em>“per-country and per-PD-band limits”</em></strong>, <strong><em>“regulatory and internal constraints”</em></strong>.</blockquote><p>Every Pareto-efficient solution x* corresponds to a different trade-off between expected return, loss and capital.</p><h3>4. How Optimization Engines Show Up in Practice 🛠️</h3><p>Pure multi-objective problems are conceptually multi-dimensional. Solvers, however, work with a <strong>single</strong> scalar objective. In practice, you typically reduce the problem in one of two ways:</p><ul><li><strong>Weighted sum (scalarization): </strong>choose weights for return, EL and capital and optimize a linear combination (for example maximize R(x) – λ_EL * EL(x) – λ_K * K(x)), or equivalently minimize λ₁ f₁(x) + λ₂ f₂(x) + …. Each choice of weights gives a different point on the Pareto frontier.</li><li><strong>Primary objective + constraints: </strong>choose one objective as primary (often expected return or a risk-adjusted version) and turn the others into hard constraints: maximize return subject to EL ≤ EL_max, capital ≤ K_max, and so on. Varying these thresholds traces out the frontier.</li></ul><p>When all relationships are linear and variables are continuous, you have a <strong>Linear Program (LP)</strong>. If some decisions are discrete (approve/decline an application, choose among a few limit buckets, pick one strategy per segment) the same structure with binary/integer variables becomes a <strong>Mixed-Integer Linear Program (MILP)</strong>.</p><p>If you add a quadratic portfolio-risk term like xᵀ Σ x, you move to a <strong>Quadratic Program (QP)</strong> and recover the familiar Markowitz-style efficient frontier in risk–return space. In credit, you can build an analogous frontier using loss covariances rather than asset returns.</p><p>In the Python demo below I stay with LP for clarity, but the conceptual structure is the same.</p><h3>5. Risk Appetite, ICAAP and How Banks Actually Use This 🏦</h3><p>In practice the weights and constraints are not arbitrary. They are tied to:</p><ul><li>the <strong>Risk Appetite Framework (RAF)</strong>,</li><li>the <strong>ICAAP</strong> and capital plan,</li><li>regulatory constraints and the strategic plan.</li></ul><p>Maximum allowed <strong>EL</strong> and <strong>capital usage</strong> are anchored to target loss ratios, regulatory capital ratios and buffers, and tolerance for earnings volatility. Minimum required <strong>return</strong> is linked to cost of capital and targets such as ROE, RoRWA or RAROC.</p><p>In other words, a portfolio optimization problem is a way to <strong>numerically encode the bank’s risk appetite</strong>:</p><ul><li>the <strong>objective</strong> captures what you want to optimize (for example a risk-adjusted return),</li><li>the <strong>constraints</strong> capture hard limits (“we simply cannot go beyond this capital/EL/concentration”).</li></ul><p>The Pareto view is powerful because it lets you check whether the <strong>portfolio implied by your current risk appetite</strong> lies on the efficient frontier, or whether you are implicitly accepting a dominated position.</p><h3>6. Limitations in Practice ⚠️</h3><p>On paper, all of this looks clean. In reality, several frictions limit how far banks can go with full-scale optimization:</p><ul><li><strong>Model risk: </strong>PD, LGD and correlations can move under stress; optimizing too aggressively on fragile estimates can be dangerous.</li><li><strong>Data and systems: </strong>lack of clean, granular data and integrated infrastructure may prevent embedding optimization in production decision engines.</li><li><strong>Computational and governance constraints: </strong>large MILPs/QPs can be heavy, and committees often prefer simple, transparent rules to a black-box optimizer.</li></ul><p>Because of this, many institutions don’t run full Pareto optimization in production. But even a <strong>simple LP/QP prototype</strong> and a <strong>visual frontier</strong> are enough to avoid dominated positions, make trade-offs explicit and align real allocations with the stated risk appetite.</p><h3>7. The Python Demo: Efficient Credit Portfolios Under Stress, Capital and Concentration Constraints 🐍</h3><p>To make all of this concrete, I built a small Python demo using numpy, pandas, cvxpy and matplotlib. The goal is to move beyond a toy “EL vs return” example and towards something that looks like a simplified <strong>risk appetite / ICAAP</strong> exercise:</p><blockquote><strong><em>Maximize expected return subject to constraints on base and stressed expected loss, capital usage and concentration.</em></strong></blockquote><p>All of this remains a linear program.</p><h4>7.1 Synthetic Segments and Risk Metrics 🧪</h4><p>We create a synthetic universe of 10 credit segments. Each segment represents a <em>country × product × risk band</em> bucket and has:</p><ul><li>a <strong>base PD</strong> between 0.5% and 5%</li><li>an <strong>LGD</strong> between 20% and 60%</li><li>a <strong>stressed PD</strong>, obtained by multiplying the base PD by a factor between 1.5 and 3 (capped at 20%)</li><li><strong>base and stressed unit EL</strong>: EL_base_i = PD_base_i * LGD_i, EL_stress_i = PD_stress_i * LGD_i</li><li>a <strong>risk weight</strong> between 30% and 120%, as a proxy for capital intensity</li><li>a <strong>country</strong> label (e.g. Country_A, Country_B, Country_C)</li><li>a <strong>PD band</strong> (Low / Medium / High) derived from the base PD</li></ul><p>Expected returns are constructed so that segments with higher base EL tend to have higher return, plus some noise.</p><p>Given any vector of portfolio weights x, we can compute:</p><ul><li>expected return R(x)</li><li>base expected loss EL_base(x)</li><li>stressed expected loss EL_stress(x)</li><li>capital usage K(x)</li><li>share of exposure in <strong>High-PD</strong> segments</li><li>share of exposure in each <strong>country</strong></li></ul><p>These are exactly the levers that a risk committee cares about.</p><h4>7.2 Optimisation Problem: Return Under Risk-Appetite Constraints 📏</h4><p>For a given cap on base expected loss EL_base_max, we solve:</p><ul><li>maximise expected return R(x)</li><li>subject to: weights sum to 1 and are non-negative, EL_base(x) ≤ EL_base_max , EL_stress(x) ≤ SF * EL_base_max (stress factor, e.g. 2.5), K(x) ≤ K_max (capital budget), share in High-PD segments ≤ γ (e.g. 40% of the book), share in any single country ≤ θ (e.g. 45%)</li></ul><p>In cvxpy, the core of this optimisation looks roughly like:</p><pre>import cvxpy as cp<br><br>x = cp.Variable(N_SEGMENTS, nonneg=True)<br><br>constraints = [cp.sum(x) == 1,<br>               EL_base @ x &lt;= EL_base_max,<br>               EL_stress @ x &lt;= SF * EL_base_max,   <br>               rw @ x &lt;= K_max,    <br>               high_pd_mask @ x &lt;= gamma,]<br><br>for c in countries:<br>    constraints.append(country_masks[c] @ x &lt;= theta)<br><br>objective = cp.Maximize(returns @ x)<br>problem = cp.Problem(objective, constraints)<br>problem.solve()</pre><p>This LP is a compact representation of a <strong>multi-dimensional risk appetite statement</strong>: control expected loss in base and stress, stay within a capital envelope, limit exposure to high-risk bands and to any single geography.</p><p>The solver returns the <strong>maximum expected return</strong> compatible with this risk appetite for the chosen EL cap.</p><h4>7.3 Tracing and Visualising the Efficient Frontier 📉</h4><p>To construct the frontier, we vary EL_base_max over a grid between the minimum and maximum base unit EL of the segments. For each value we:</p><ul><li>solve the LP above with fixed stress factor, capital budget and concentration limits</li><li>record base EL, stressed EL, capital usage and expected return for the optimal portfolio</li></ul><p>Plotting expected return against base EL across this grid gives the <strong>efficient frontier</strong> in EL–return space under all constraints.</p><p>To give some context, we also generate a cloud of <strong>random feasible portfolios</strong>:</p><ul><li>we draw random weights from a Dirichlet distribution,</li><li>we keep only those that satisfy the same capital, stress and concentration limits,</li><li>we compute their base EL and expected return and plot them as a scatter.</li></ul><p>On the chart, these random portfolios form a cloud of feasible choices. The optimized portfolios form a smooth curve sitting on top of that cloud: the efficient frontier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*VMLYcz4TetVtuM2f70AiHQ.png" /><figcaption><strong><em>Figure 1 — Efficient frontier in EL–return space.</em></strong><em><br> The dots represent random feasible portfolios satisfying the same capital, stress and concentration constraints. The solid line shows the efficient frontier: for each level of expected loss, it is the portfolio with the maximum achievable return under the chosen risk appetite.</em></figcaption></figure><h4>7.4 What the Results Mean for Management 🧑‍💼</h4><p>In the synthetic run, the behaviour of the model is intuitive.</p><p>At the <strong>conservative end</strong> of the frontier (lowest EL cap), the optimal portfolio places most of the exposure in <strong>Low-PD segments</strong>, complemented by some <strong>Medium-PD</strong> names and only a small slice of <strong>High-PD</strong> (around 10%). Base and stressed EL both remain low, capital usage is moderate, and country exposures are comfortably within their limits. This is exactly the kind of prudently diversified portfolio that matches a conservative risk appetite.</p><p>At the <strong>aggressive end</strong> of the frontier (highest EL cap), the solution concentrates on a small set of <strong>higher-PD, higher-return</strong> segments. The share of High-PD exposure moves right up to the appetite limit (40%), country exposures run close to — but never above — their caps, and the capital budget is fully utilised. This portfolio sits at the edge of what the bank is willing to tolerate in terms of risk, while still remaining compliant with stress, capital and concentration constraints.</p><p>In the EL–return space, the efficient frontier sends a clear message to management: points on the curve represent the <strong>best achievable portfolios</strong> under the stated risk appetite; points below the curve are <strong>dominated choices</strong> with an inferior risk–return trade-off; and moving along the frontier makes explicit <strong>how much additional expected loss and capital</strong> are required to obtain a given increase in portfolio return.</p><h3>8. Conclusion ✅</h3><p>Credit risk is rarely about “maximize one number”. It is about <strong>balancing</strong> expected return, expected loss, capital usage, volatility and concentration under regulatory and strategic constraints.</p><p>The key ideas of this article are:</p><ul><li><strong>Pareto optimality</strong> is a realistic way to think about credit-portfolio decisions: efficient portfolios lie on a frontier; everything below it is dominated.</li><li><strong>Optimization engines</strong> like LP (and, where needed, MILP/QP) compute efficient trade-offs once you specify objectives (return, EL, capital, risk) and constraints (budgets, limits, risk appetite).</li><li>Even a relatively simple Python prototype can reveal your efficient frontier, highlight dominated positions and help you align practice with your Risk Appetite Framework.</li></ul><p>Models give you PD, LGD and EAD.<br> <strong>Multi-objective optimization and Pareto let you turn those numbers into defensible, efficient portfolio decisions.</strong></p><blockquote><em>📥 </em><strong><em>Explore the full implementation</em></strong><em> on GitHub → </em><a href="https://github.com/fabiodigiovanni/from-pd-to-pareto">https://github.com/fabiodigiovanni/from-pd-to-pareto</a></blockquote><h3>Let’s Connect!</h3><p>If you enjoyed this article and want to dive deeper into credit risk management, follow me on <a href="https://www.linkedin.com/in/fabio-di-giovanni/">LinkedIn</a>. I’d love to connect and continue the conversation!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b1ac3f3a5d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Credit Scorecard Development: Part 3 — From Logistic Regression to Machine Learning…]]></title>
            <link>https://medium.com/@fabiodigiovanni97/mastering-credit-scorecard-development-part-3-from-logistic-regression-to-machine-learning-466ae312922b?source=rss-44319ea4bb38------2</link>
            <guid isPermaLink="false">https://medium.com/p/466ae312922b</guid>
            <category><![CDATA[credit-score]]></category>
            <category><![CDATA[risk-management]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Fabio Di Giovanni]]></dc:creator>
            <pubDate>Fri, 20 Jun 2025 06:35:32 GMT</pubDate>
            <atom:updated>2025-06-24T18:10:41.215Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Credit Scorecard Development: Part 3 — From Logistic Regression to Machine Learning Models</h3><h4>Can machine learning outperform traditional scorecards without sacrificing transparency? We put it to the test</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YaEAUBg2VEgOjBuC43umIA.jpeg" /></figure><p>After laying the theoretical foundations in <a href="https://medium.com/@fabiodigiovanni97/mastering-credit-scorecard-development-part-1-a-theoretical-guide-1de33a66c2fd"><strong>Part 1</strong></a><strong> </strong>— focusing on logistic regression, Weight of Evidence (WOE), and score-driven decision-making — and building a transparent scorecard in <a href="https://medium.com/@fabiodigiovanni97/mastering-credit-scorecard-development-part-2-from-data-to-risk-driven-insights-f21cf5ae667a"><strong>Part 2</strong></a>, we now take the next step. In this final part, we compare logistic regression with more advanced machine learning models like Random Forest and XGBoost to explore the trade-offs between predictive power and interpretability in real-world credit risk applications.</p><h3>Experimental Setup ⚙️</h3><p>To ensure a fair comparison across models, we reused the same dataset and preprocessing pipeline introduced in Part 2. This includes supervised binning using the Chi-squared method and Weight of Evidence (WOE) transformation applied to all features. The final dataset contains variables such as annual income, loan amount, term, and credit history indicators — each encoded for interpretability and consistency.</p><p>The data was split into training and test sets using a 67/33 ratio via train_test_split, with a fixed random state for reproducibility.</p><pre>train, test = train_test_split(df, test_size=0.33, random_state=42)</pre><p>Instead of performing hyper-parameter tuning, which can introduce complexity and obscure the core comparisons, we opted for default or commonly used settings for both Random Forest and XGBoost. This keeps the focus on model behavior rather than optimization.</p><p>To evaluate performance, we relied on standard classification metrics:</p><ul><li><strong>AUC (Area Under the Curve): </strong>Measures a model’s ability to distinguish between classes. Higher AUC = better overall performance.</li><li><strong>Confusion Matrix: </strong>A table showing correct vs incorrect predictions broken down by class (True Positive, False Positive, False Negative, True Negative).</li><li><strong>F1-score: </strong>The harmonic mean of precision and recall. It balances the trade-off between false positives and false negatives, making it especially useful when dealing with imbalanced classes.</li></ul><p>These metrics provide a well-rounded view of model performance, especially in credit risk contexts where false positives and false negatives carry different business implications.</p><blockquote>📂 <strong>Full Code on GitHub</strong><br> You can find the complete codebase, including preprocessing, modeling, and evaluation visuals, here: <a href="https://github.com/fabiodigiovanni/scorecard-implementation">https://github.com/fabiodigiovanni/scorecard-implementation</a></blockquote><h3>Model Overview 🧠</h3><p>This section introduces the three models evaluated in our comparison, focusing on their core mechanics and interpretability in a credit risk context.</p><h4>Logistic Regression (Baseline)</h4><p>Logistic regression models the probability of default as a function of input features X using the logistic function.</p><p>In our setup, the features are WOE-transformed, which ensures a linear relationship with the log-odds. Each coefficient βᵢ represents the change in log-odds of default for a one-unit increase in the corresponding WOE feature. This allows for full model transparency and straightforward interpretability — two critical aspects in regulated credit environments.</p><pre>lr = LogisticRegression(class_weight=None, max_iter=1000, random_state=42)<br><br>lr.fit(X_train, y_train)<br><br>y_train_pred = lr.predict(X_train)<br>y_test_pred = lr.predict(X_test)</pre><h4>Random Forest</h4><p>Random Forest is an ensemble method that combines multiple decision trees trained on bootstrapped samples of the data. At each split in a tree, a random subset of features is considered. The final prediction is obtained via majority voting for classification tasks.</p><p>Mathematically, it can be expressed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*czfPVQbptIPZYqK-2ms8hg.png" /></figure><p>where Tₖ(x) is the prediction of the k-th decision tree. While not inherently interpretable, Random Forest provides feature importance scores based on metrics like Gini impurity, helping identify key predictors.</p><pre>rf_clf = RandomForestClassifier(n_estimators=100)<br><br>rf_clf.fit(X_train, y_train)<br><br>y_train_pred = rf_clf.predict(X_train)<br>y_test_pred = rf_clf.predict(X_test)</pre><h4>XGBoost</h4><p>XGBoost is a gradient boosting algorithm that builds an ensemble of decision trees in a sequential manner. At each iteration, a new tree is trained to minimize the residual errors of the previous model, using gradient descent on a specified loss function. For binary classification tasks like credit scoring, this is typically the logistic loss:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*BimelTpxxqeCIYIwsGey0A.png" /></figure><p>where:</p><ul><li>l is the loss function,</li><li>fₜ is the tree added at iteration t,</li><li>Ω(fₜ) is a regularization term controlling tree complexity (e.g., depth, number of leaves).</li></ul><pre>xgb_clf = XGBClassifier(use_label_encoder=False)<br><br>xgb_clf.fit(X_train, y_train)<br><br>y_train_pred = xgb_clf.predict(X_train)<br>y_test_pred = xgb_clf.predict(X_test)</pre><p>Although XGBoost is less interpretable than logistic regression, it can be explained using tools like <strong>SHAP values</strong>, which are based on <strong>cooperative game theory</strong>. In this context, each feature is treated like a “player” in a game, and the goal is to fairly determine how much each feature contributed to the model’s final prediction. SHAP assigns each feature a value that reflects its individual impact, helping us understand why the model made a specific decision, even when the model itself is complex.</p><h3>Results: Performance Comparison 📊</h3><p>Below, we summarize the results with visual comparisons and performance metrics to highlight how each model performed on the credit default prediction task.</p><h4>ROC Curve Comparison</h4><p>The ROC curves (Figure 1) clearly show that both XGBoost and Random Forest outperform logistic regression in terms of AUC:</p><ul><li><strong>Logistic Regression</strong>: AUC = 0.88</li><li><strong>Random Forest</strong>: AUC = 0.89</li><li><strong>XGBoost</strong>: AUC = 0.90</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*KHeNpAbMF1PA7yOtWE2lGw.png" /><figcaption>Figure 1: Comparison of ROC Curves</figcaption></figure><p>XGBoost exhibits the best discriminative ability, especially in the low false positive rate region, which is critical in credit risk contexts.</p><h4>Train vs Test ROC AUC</h4><p>As shown in Figure 2, all models generalize well, but Random Forest shows a slightly higher training AUC, hinting at mild overfitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*LdlUFCXg2hzfnnzYK1Ausw.png" /><figcaption>Figure 2: ROC Scores of Models (Test &amp; Train sets)</figcaption></figure><h4>Performance Metrics on the Test Set</h4><p>To complement the ROC analysis, we evaluated all three models on the test set using standard classification metrics. While overall accuracy remains similar, the differences in precision, recall, and AUC reveal each model’s unique strengths.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*0Inf_djN2UQqpB4iWihKVw.png" /></figure><p>All three models achieve nearly identical accuracy, but subtle differences emerge in how they handle class predictions:</p><ul><li><strong>XGBoost</strong> achieves the highest <strong>AUC</strong> and <strong>precision</strong>, slightly edging out the others in <strong>predictive power</strong>.</li><li><strong>Random Forest</strong> delivers strong recall and a balanced F1-score, but shows slight overfitting when comparing train and test scores.</li><li><strong>Logistic Regression</strong>, while the simplest model, performs competitively and reaches the <strong>highest recall</strong>, making it effective for minimizing false negatives, a crucial factor in credit risk.</li></ul><h3>Interpreting the Trade-Off 🔍</h3><p>While machine learning models like XGBoost and Random Forest outperform logistic regression in terms of predictive power, they raise important questions about <strong>interpretability</strong>, <strong>regulatory compliance</strong>, and <strong>operational cost</strong>.</p><p>In highly regulated environments, such as credit risk scoring under <strong>Basel III/IV</strong> guidelines, transparency is not optional. Logistic regression remains the gold standard because it produces clear, auditable models that directly align with business logic. Each coefficient has a meaningful interpretation, making model decisions explainable to risk officers, auditors, and regulators.</p><p>Interpretability is evolving. While <strong>Random Forest</strong> and <strong>XGBoost </strong>are not inherently transparent, they provide <strong>feature importance scores</strong> that highlight which variables drive predictions overall. More advanced tools — like <strong>SHAP values</strong> — go further, offering <strong>local explanations</strong> by quantifying each feature’s contribution to individual predictions. <strong>Partial dependence plots</strong> also help by visualizing how specific features influence the model’s output across their range. These tools help bridge the gap between performance and explainability, making ML models increasingly viable for production use in risk-sensitive contexts.</p><p>There is also growing interest in <strong>hybrid approaches</strong> — for example, using XGBoost to identify optimal variable transformations or bins, and then training a <strong>logistic regression</strong> on those engineered features. This can provide a balance between predictive strength and transparency, as noted in recent publications.</p><p>Ultimately, the choice of model depends on context:</p><ul><li><strong>Choose logistic regression</strong> when interpretability, simplicity, and regulatory clarity are key priorities.</li><li><strong>Choose ML models</strong> like XGBoost when maximizing prediction accuracy is critical, and when explainability tools are in place to support transparency.</li></ul><p>In practice, risk teams can adopt a layered strategy:</p><ul><li>Use ML models for <strong>challenger modelling</strong>, performance benchmarking, or risk-based segmentation.</li><li>Deploy interpretable models for <strong>production scoring</strong>, with periodic reviews and <strong>model audits</strong>.</li><li>Introduce governance frameworks around <strong>ML retraining</strong>, <strong>monitoring</strong>, and <strong>fairness testing</strong>.</li></ul><p>In the end, it’s not about picking a side. It’s about using the right model for the right task — and often, combining them. Whether you’re deploying a scorecard or building a challenger model, knowing the trade-offs is what turns a model into a strategy.</p><h3>Conclusion and Future Directions 🧾</h3><p>This third and final part of the series has highlighted how advanced machine learning models — specifically Random Forest and XGBoost — can outperform traditional logistic regression in predictive accuracy when building credit scorecards. Among the three, XGBoost demonstrated the highest AUC and F1-score, while logistic regression remained the most interpretable and regulation-friendly option.</p><p>For credit risk teams, the message is clear: model selection is not just about performance metrics. It involves a broader consideration of explainability, compliance, operational complexity, and business context. Logistic regression continues to offer a transparent, scalable, and trusted solution, especially where auditability is critical. However, when used responsibly, machine learning models can bring added predictive value and support more nuanced credit decisions.</p><p>Looking ahead, several promising directions emerge:</p><ul><li><strong>Hybrid modelling strategies</strong> that combine the structure of logistic regression with the feature discovery power of ML algorithms.</li><li><strong>Time-aware models</strong> that incorporate temporal dynamics into credit risk modelling.</li><li><strong>Fairness and robustness analysis</strong> to ensure that advanced models perform equitably across demographic segments and remain stable under changing conditions.</li></ul><p>As credit risk modelling evolves, the key will be maintaining a balance between <strong>statistical power</strong>, <strong>regulatory transparency</strong>, and <strong>real-world usability</strong>. The future isn’t just about choosing between interpretable and complex models — it’s about <strong>integrating both strategically</strong> to make smarter, safer credit decisions.</p><blockquote>📥 <strong>Explore the full implementation</strong> on GitHub → <a href="https://github.com/fabiodigiovanni/scorecard-implementation">https://github.com/fabiodigiovanni/scorecard-implementation</a></blockquote><h3>Let’s Connect!</h3><p>If you enjoyed this article and want to dive deeper into credit risk management, follow me on <a href="https://www.linkedin.com/in/fabio-di-giovanni/">LinkedIn</a>. I’d love to connect and continue the conversation!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=466ae312922b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Credit Scorecard Development: Part 2 — From Data to Risk-Driven Insights]]></title>
            <link>https://medium.com/@fabiodigiovanni97/mastering-credit-scorecard-development-part-2-from-data-to-risk-driven-insights-f21cf5ae667a?source=rss-44319ea4bb38------2</link>
            <guid isPermaLink="false">https://medium.com/p/f21cf5ae667a</guid>
            <category><![CDATA[risk-management]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[credit-risk-modelling]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <dc:creator><![CDATA[Fabio Di Giovanni]]></dc:creator>
            <pubDate>Tue, 27 May 2025 07:24:57 GMT</pubDate>
            <atom:updated>2025-06-24T18:10:15.173Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Credit Scorecard Development: Part 2 — From Data to Risk-Driven Insights</h3><h4>Transforming Theory into Action: A Risk-Driven Framework for Building Credit Scorecards Using Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rhPK74L2ScWpr2Vt1fNMzg.jpeg" /></figure><p>Credit scorecards are a cornerstone of credit risk assessment, helping institutions quantify borrower risk in a transparent and standardized way. In <a href="https://medium.com/@fabiodigiovanni97/mastering-credit-scorecard-development-part-1-a-theoretical-guide-1de33a66c2fd"><strong>Part 1</strong></a>, we explored the theoretical foundations focusing on logistic regression, Weight of Evidence (WOE), and score-driven decision-making.</p><p>In this second part, we move from theory to practice, walking through a real-world implementation. We’ll explain how to prepare data, define the target variable, transform features for interpretability, and build a scorecard that reflects creditworthiness.</p><p>While we focus on logistic regression for its balance of simplicity and transparency, <a href="https://medium.com/@fabiodigiovanni97/mastering-credit-scorecard-development-part-3-from-logistic-regression-to-machine-learning-466ae312922b"><strong>Part 3</strong></a> will compare it with more complex machine learning models to explore trade-offs in predictive power and interpretability.</p><p>By the end, you’ll understand how to build a practical, explainable, and business-aligned credit scorecard.</p><h3>Framing the Problem: Predicting Risk Without Overfitting</h3><p>In credit risk modelling, the objective isn’t just to fit a model to past data — it’s to create a system that generalizes to future borrowers. That’s where the art of scorecard development lies: balancing predictive power with long-term reliability and interpretability.</p><p>Even clean data can be misleading. Some variables may correlate with default temporarily but fail to capture stable risk patterns. For instance, an applicant’s recent job switch might temporarily correlate with higher defaults, yet may not reflect long-term risk<em>.</em> Others risk introducing noise or spurious relationships, undermining the model’s robustness.</p><p>The challenge is twofold: select variables with a consistent, explainable link to credit risk, and transform them in a way that preserves clarity for credit officers, auditors, and regulators — all without compromising performance.</p><p>By adopting this mindset, we shift from a purely algorithmic approach to a modelling philosophy rooted in business logic, risk management, and long-term trust.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ve2K_1Jss2dwL-J30SKehw.png" /><figcaption><em>Loan Distribution and Status Over Time</em></figcaption></figure><h3>Preparing Data for Risk Modelling</h3><p>Before building a credit scorecard, it’s essential to preprocess the data in a way that ensures statistical reliability and business interpretability.</p><h4>Feature Selection</h4><p>We begin by identifying which variables are significantly associated with credit outcomes. For <strong>categorical features</strong>, we use the <strong>Chi-squared test</strong>, which assesses independence between the feature and the target variable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*kVJE93CHyaiPgUMzIE5OuA.png" /></figure><p>where Oᵢⱼ and Eᵢⱼ​ are the observed and expected frequencies. Features with high p-values (typically p≥0.5) are considered weak predictors and excluded.</p><p>For <strong>numerical features</strong>, we apply the <strong>ANOVA F-statistic</strong>, which compares the means of a feature across the two loan classes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*YrCwlnuCxbSK2Lldqj8E7A.png" /></figure><p>A low p-value suggests the feature is meaningfully different between defaulters and non-defaulters, making it a valuable predictor.</p><pre>def feature_selection_iv_summary(X_train, y_train):<br>    X_train_cat = X_train.select_dtypes(include=&#39;object&#39;).copy()<br>    X_train_num = X_train.select_dtypes(include=&#39;number&#39;).copy()<br><br>    X_train_num.fillna(X_train_num.mean(), inplace=True)<br><br>    chi2_check = {&#39;Feature&#39;: [], &#39;Test Type&#39;: [], &#39;p-value&#39;: []}<br>    for column in X_train_cat:<br>        chi, p, dof, ex = chi2_contingency(pd.crosstab(y_train, X_train_cat[column]))<br>        chi2_check[&#39;Feature&#39;].append(column)<br>        chi2_check[&#39;Test Type&#39;].append(&quot;Chi-squared&quot;)<br>        chi2_check[&#39;p-value&#39;].append(round(p, 10))<br><br>    chi2_result = pd.DataFrame(data=chi2_check)<br><br>    F_statistic, p_values = f_classif(X_train_num, y_train)<br>    anova_result = pd.DataFrame(data={<br>        &#39;Feature&#39;: X_train_num.columns.values,<br>        &#39;Test Type&#39;: &#39;ANOVA F&#39;,<br>        &#39;p-value&#39;: p_values.round(decimals=10)})<br><br>    feature_stats = pd.concat([chi2_result, anova_result], ignore_index=True)<br><br>    feature_stats.sort_values(by=[&#39;Test Type&#39;, &#39;p-value&#39;], ascending=[True, True], ignore_index=True, inplace=True)<br><br>    return feature_stats</pre><h4>Multicollinearity Control</h4><p>To avoid redundancy, we compute correlations between all pairs of features. Depending on variable types, we use:</p><ul><li><strong>Pearson’s r</strong> for numerical-numerical pairs</li><li><strong>Cramér’s V</strong> for categorical-categorical pairs:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*L-w8d-MsUiwI-qt5sW6cZg.png" /></figure><ul><li><strong>Correlation ratio η</strong> for categorical-numerical pairs:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/237/1*tKjdBcIYvq34yyt3RoQ1zQ.png" /></figure><p>Features with correlations exceeding a threshold (e.g. ∣r∣&gt;0.8) are dropped to maintain model stability.</p><pre>def cramers_v(x, y):<br>    &quot;&quot;&quot;Calculate Cramér&#39;s V for categorical-categorical associations.&quot;&quot;&quot;<br>    confusion_matrix = pd.crosstab(x, y)<br>    chi2 = chi2_contingency(confusion_matrix)[0]<br>    n = confusion_matrix.sum().sum()<br>    phi2 = chi2 / n<br>    r, k = confusion_matrix.shape<br>    phi2corr = max(0, phi2 - ((k - 1) * (r - 1)) / (n - 1))<br>    rcorr = r - ((r - 1) ** 2) / (n - 1)<br>    kcorr = k - ((k - 1) ** 2) / (n - 1)<br>    return np.sqrt(phi2corr / min((kcorr - 1), (rcorr - 1)))<br><br>def correlation_ratio(categories, measurements):<br>    &quot;&quot;&quot;Calculate the correlation ratio (eta squared) for categorical-numerical associations.&quot;&quot;&quot;<br>    fcat, _ = pd.factorize(categories)<br>    cat_num = np.max(fcat) + 1<br>    y_avg = np.mean(measurements)<br>    numerator = np.sum([len(measurements[fcat == i]) * (np.mean(measurements[fcat == i]) - y_avg) ** 2 for i in range(cat_num)])<br>    denominator = np.sum((measurements - y_avg) ** 2)<br>    return np.sqrt(numerator / denominator)<br><br>def multicollinearity_matrix(X_train):<br>    num_features = X_train.select_dtypes(include=[np.number]).columns<br>    cat_features = X_train.select_dtypes(include=[&#39;object&#39;, &#39;category&#39;]).columns<br><br>    corr_matrix = pd.DataFrame(index=X_train.columns, columns=X_train.columns)<br><br>    for col1 in X_train.columns:<br>        for col2 in X_train.columns:<br>            if col1 == col2:<br>                corr_matrix.loc[col1, col2] = 1.0<br>            elif not pd.isna(corr_matrix.loc[col2, col1]):<br>                corr_matrix.loc[col1, col2] = corr_matrix.loc[col2, col1]<br>            else:<br>                if col1 in num_features and col2 in num_features:<br>                    corr = X_train[col1].corr(X_train[col2])<br><br>                elif col1 in cat_features and col2 in cat_features:<br>                    corr = cramers_v(X_train[col1], X_train[col2])<br><br>                elif col1 in cat_features and col2 in num_features:<br>                    corr = correlation_ratio(X_train[col1], X_train[col2])<br>                <br>                elif col1 in num_features and col2 in cat_features:<br>                    corr = correlation_ratio(X_train[col2], X_train[col1])<br>                <br>                corr_matrix.loc[col1, col2] = round(corr, 4)<br><br>    corr_matrix = corr_matrix.apply(pd.to_numeric)<br><br>    plt.figure(figsize=(12, 10))<br>    sns.heatmap(corr_matrix, annot=True, cmap=&#39;coolwarm&#39;, fmt=&quot;.2f&quot;, linewidths=0.5)<br>    plt.title(&#39;Multicollinearity Matrix (Numerical and Categorical)&#39;)<br>    plt.show()<br><br>    return corr_matrix<br><br>def identify_high_multicollinearity(corr_matrix, threshold=0.8):<br>    to_drop = set()<br>    already_checked = set()<br><br>    for col in corr_matrix.columns:<br>        for row in corr_matrix.index:<br>            if col != row and abs(corr_matrix.loc[row, col]) &gt; threshold:<br>                if row not in already_checked:<br>                    to_drop.add(col)<br>                    already_checked.add(col)<br>    <br>    return list(to_drop)</pre><h4>Other Preprocessing Steps</h4><ul><li><strong>Categorical variables</strong> are one-hot encoded to retain interpretability in logistic regression.</li><li><strong>Outliers</strong> in key variables (e.g. income, balance) are removed to prevent distortion of model coefficients.</li></ul><h3>Discretization: Why Binning Isn’t Just a Preprocessing Step</h3><p>In credit scoring, continuous variables often need to be transformed for clarity and compliance, this is where <strong>supervised binning</strong> proves essential.</p><p>The core idea behind binning is simple: we divide a continuous variable (like annual income or loan amount) into discrete intervals, or <em>bins</em>. However, rather than doing so arbitrarily, we rely on <strong>ChiMerge</strong>, a supervised binning technique that uses the Chi-squared statistic to guide how bins are formed. The algorithm merges adjacent intervals that have statistically similar distributions of good and bad loans, stopping when further merging would lead to a loss in discriminatory power.</p><pre>combiner = toad.transform.Combiner()<br>combiner.fit(X_train, y_train, method=&#39;chi&#39;, min_samples=0.005)<br><br>X_train_binned = combiner.transform(X_train)<br>X_test_binned = combiner.transform(X_test)</pre><p>Each merge step reduces the number of bins while preserving segments where the difference in default rate is statistically significant.</p><p>Binning is more than a convenience; it serves three strategic purposes:</p><ol><li><strong>Risk Pattern Isolation</strong>: Turns numeric variables into ordered categories that reveal how risk changes across ranges. This enhances interpretability, especially in regulated environments.</li><li><strong>Monotonicity Enforcement</strong>: Helps ensure a consistent relationship between variable values and default risk, crucial for interpretability. This simplifies interpretation: as income increases, default risk consistently decreases — no unexpected reversals.</li><li><strong>Controlled Granularity:</strong> The level of bin granularity must be chosen carefully. Too many bins can lead to overfitting and spurious risk signals, while too few can oversimplify important distinctions. Setting a minimum bin size (e.g., min_samples = 0.5% of the dataset) helps ensure that each bin is statistically stable. Importantly, this threshold should be adapted based on the size of the dataset—larger datasets can support finer granularity, while smaller datasets require more conservative binning to maintain reliability.</li></ol><p>Ultimately, binning helps bridge the gap between raw data and explainable modelling. It enables credit risk practitioners to work with variables that reflect true economic behaviour, while maintaining the structure needed for robust statistical inference.</p><h3>Weight of Evidence: Turning Raw Features into Risk Predictors</h3><p>After discretizing continuous variables into bins, the next step is to quantify their relationship with credit risk using <strong>Weight of Evidence (WOE)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*FJ_-PwhrzAQid-fpgDOZGA.png" /></figure><p>This transformation assigns a numeric value to each bin, capturing the strength and direction of its association with the target (default vs. no default). The code below applies WOE:</p><pre>t = toad.transform.WOETransformer()<br>X_train = t.fit_transform(X_train_binned, y_train)<br>X_test = t.transform(X_test_binned)</pre><p>WOE values are centered around zero: positive values indicate lower risk, while negative values signal higher risk.</p><h4><strong>Why WOE Matters</strong></h4><p>WOE offers key benefits for scorecard development:</p><ul><li><strong>Linearity in Log-Odds</strong>: Because logistic regression models the log-odds of default, WOE-transformed variables tend to have a more linear relationship with the outcome, improving model performance and interpretability.</li><li><strong>Scale Uniformity</strong>: All WOE-transformed variables are on the same conceptual scale (log odds), which makes their coefficients directly comparable and the model easier to interpret.</li><li><strong>Handling Class Imbalance</strong>: WOE inherently adjusts for the imbalance between good and bad loans. Even in datasets where defaults are rare, WOE transformation highlights risk signals by comparing the relative proportions within each bin.</li></ul><p>In short, WOE turns qualitative patterns into quantitative insights. It preserves interpretability while aligning perfectly with the statistical foundations of logistic regression. In regulated environments where transparency is key, WOE is more than a transformation — it’s a vital layer of explainability.</p><h3>From Information to Scores: The Role of Logistic Regression</h3><p><strong>Logistic regression</strong> is often underrated for its simplicity, yet it’s ideally suited for transparent and interpretable credit risk modelling. When paired with Weight of Evidence (WOE)-transformed features, <strong>it becomes more than a model</strong>, it becomes a clear <strong>mapping from human-understandable risk categories to data-driven decisions</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*bU0yPN95nZaJ3TKtfjjRIA.png" /></figure><p>Because WOE inputs are linear in the log-odds by design, each variable contributes proportionally and additively to the default probability estimate. This aligns well with both statistical theory and operational logic.</p><h4>Logistic Regression in Practice</h4><p>In our implementation, we trained a logistic regression model using scikit-learn’s LogisticRegression with increased iterations for convergence and no class weighting:</p><pre>lr = LogisticRegression(class_weight=None, max_iter=1000, random_state=42)<br><br>lr.fit(X_train, y_train)<br><br>y_train_pred = lr.predict(X_train)<br>y_test_pred = lr.predict(X_test)</pre><p>We then generated predictions and probabilities, evaluating performance with two essential tools: the <strong>ROC curve</strong> and the <strong>confusion matrix</strong>. The ROC curve illustrates the trade-off between sensitivity and specificity, while the Area Under the Curve (AUC) quantifies overall discriminatory power.</p><p>A high AUC means the model can effectively distinguish good borrowers from risky ones, critical in any credit strategy. In our case, the model reached an <strong>AUC of 0.88</strong>, as shown in the figure. This reflects strong predictive capability while maintaining full interpretability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZhKzg5k5CrV23s8lw7Pirw.png" /></figure><h4>From Probabilities to Scores</h4><p>To transform model outputs into an actionable credit scorecard, we used toad.ScoreCard, which converts log-odds into a point-based scoring system. This is achieved through a <strong>base score</strong> (e.g., 800) and a <strong>Points to Double the Odds (PDO)</strong> parameter that defines the scaling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*cXfhnrqYS6IG_jFVe58jAw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*08Na9ZyvR7hRCtOxKX7Lmg.png" /></figure><pre>card = toad.ScoreCard(<br>    combiner = combiner,<br>    transer = t,<br>    class_weight = &#39;balanced&#39;,<br>    C=0.1,<br>    base_score = 800,<br>    base_odds = 35 ,<br>    pdo = 20,<br>    rate = 2)<br><br>card.fit(X_train, y_train)<br>final_card = card.export(to_frame=True)</pre><p>Each variable bin is assigned a point value, allowing credit officers to interpret results without dealing with probabilities. For example, a higher income bracket might contribute +40 points to the final score, while a recent default could subtract -60<em>.</em> These point values make the scorecard transparent, auditable, and usable by non-technical stakeholders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*iHjfeNCDf19FmwwAWwBwPw.png" /></figure><h3>Conclusion: From Theory to Practice Without Losing Transparency</h3><p>In this second part, we demonstrated how to build a credit scorecard using interpretable, theory-driven methods. By combining Weight of Evidence with logistic regression, we created a model that balances <strong>predictive accuracy</strong> with <strong>transparency </strong>and is ready for real-world use and regulatory review.</p><p>Crucially, we achieved this without relying on complex machine learning. The result is a robust, scalable, and explainable tool — exactly what credit risk environments demand.</p><p>In <a href="https://medium.com/@fabiodigiovanni97/mastering-credit-scorecard-development-part-3-from-logistic-regression-to-machine-learning-466ae312922b"><strong>Part 3</strong></a>, we’ll push further, comparing this approach to <strong>advanced ML models</strong> to explore the trade-offs between accuracy, interpretability, and practical decision-making.</p><h3>Let’s Connect!</h3><p>If you enjoyed this article and want to dive deeper into credit risk management, follow me on <a href="https://www.linkedin.com/in/fabio-di-giovanni/">LinkedIn</a>. I’d love to connect and continue the conversation!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f21cf5ae667a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Credit Scorecard Development: Part 1 — A Theoretical Guide]]></title>
            <link>https://medium.com/@fabiodigiovanni97/mastering-credit-scorecard-development-part-1-a-theoretical-guide-1de33a66c2fd?source=rss-44319ea4bb38------2</link>
            <guid isPermaLink="false">https://medium.com/p/1de33a66c2fd</guid>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[risk-assessment]]></category>
            <category><![CDATA[risk-management]]></category>
            <category><![CDATA[credit-risk-management]]></category>
            <category><![CDATA[credit-score]]></category>
            <dc:creator><![CDATA[Fabio Di Giovanni]]></dc:creator>
            <pubDate>Fri, 20 Dec 2024 11:36:14 GMT</pubDate>
            <atom:updated>2025-06-24T18:09:48.308Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Mastering Credit Scorecard Development: Part 1 — A Theoretical Guide</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BOveczB2uBpLeJ3Y6gRx7Q.png" /></figure><p>Credit scorecards play a pivotal role in assessing borrowers’ creditworthiness, helping financial institutions make data-driven decisions. Simply put, a credit scorecard assigns a numerical score to borrowers based on factors like income, credit history, and repayment behaviour. Higher scores typically indicate lower risk, leading to more favourable terms for borrowers.</p><p>In this article, we’ll lay the theoretical groundwork for credit scorecard development, covering key concepts, challenges, and ethical considerations. In <a href="https://medium.com/@fabiodigiovanni97/mastering-credit-scorecard-development-part-2-from-data-to-risk-driven-insights-f21cf5ae667a"><strong>Part 2</strong></a>, we’ll implement a credit scorecard in Python, delving into data preprocessing, model building, and evaluation. Finally, in <a href="https://medium.com/@fabiodigiovanni97/mastering-credit-scorecard-development-part-3-from-logistic-regression-to-machine-learning-466ae312922b"><strong>Part 3</strong></a>, we’ll explore how artificial intelligence can further enhance credit scorecards, unlocking greater accuracy and decision-making potential. Let’s begin this structured, hands-on journey into credit scorecard development!</p><h3>What is a Credit Scorecard?</h3><p>A <strong>credit scorecard</strong> is a statistical tool that evaluates a borrower’s creditworthiness by assigning a numerical score based on predictive factors like income, credit history, and repayment behaviour. This score reflects the borrower’s likelihood of meeting financial obligations, enabling lenders to make informed credit decisions.</p><h4>The History and Evolution of Credit Scoring</h4><p>Credit scoring emerged in the mid-20th century to address the subjectivity of traditional lending practices. Over the decades, it has evolved significantly:</p><ul><li><strong>1950s</strong>: Statistical methods were introduced to credit assessment, forming the foundation of modern scorecards.</li><li><strong>1960s</strong>: Companies like Fair Isaac Corporation (FICO) pioneered standardized credit scoring systems, revolutionizing risk management.</li><li><strong>2000s and Beyond</strong>: Advances in computing power and data availability have enabled sophisticated models that leverage machine learning and big data for improved accuracy and scalability.</li></ul><h4>Key Benefits of Credit Scorecards</h4><ol><li><strong>Objectivity</strong>: Statistical methods minimize biases, ensuring consistent evaluations across borrowers.</li><li><strong>Consistency</strong>: Uniform criteria reduce variability in decision-making, aiding regulatory compliance.</li><li><strong>Scalability</strong>: Automated scoring systems process large application volumes efficiently, which is critical for high-growth markets.</li></ol><h3>Key Concepts in Credit Scoring</h3><h4>Risk Differentiation</h4><p>Credit scorecards quantify lending risks by transforming complex data into actionable scores. They distinguish between high-risk and low-risk borrowers by analyzing historical patterns:</p><ul><li><strong>High-risk borrowers</strong>: Lower scores due to factors like late payments or high debt levels.</li><li><strong>Low-risk borrowers</strong>: Higher scores reflecting positive repayment behaviour and financial stability.</li></ul><h4>Probability of Default (PD)</h4><p>The <strong>Probability of Default</strong> estimates the likelihood that a borrower will default on their obligations. <strong>Logistic regression</strong> is a common method for calculating PD, using predictors such as age, income, and credit history:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*fFb3flYSwITPTA7ydDhUrA.png" /></figure><ul><li>X₁, X₂, …, Xₙ: Predictors like age, income, or credit history.</li><li>β₀, β₁, …, βₙ: Model coefficients derived from historical data.</li></ul><h4>Characteristics and Attributes</h4><p>Credit scorecards rely on <strong>characteristics</strong> (e.g., income, age) and their <strong>attributes</strong> (specific values within these categories). For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*pP-fDWKOz-yjgVzDfn4Tyw.png" /><figcaption>Source: <a href="https://www.lancaster.ac.uk/">https://www.lancaster.ac.uk</a></figcaption></figure><p>Each attribute is assigned a <strong>Weight of Evidence (WoE)</strong> value, quantifying its contribution to risk assessment. WoE can be calculated using the formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*8r4M3zfTdZ4F79_CQVWTjg.png" /></figure><p>Here, “Goods” represent borrowers who do not default, and “Bads” represent those who do.</p><h3>Types of Scorecards</h3><ul><li><strong>Application Scorecards</strong>: Evaluate new applicants using demographic and credit bureau data.</li><li><strong>Behavioural Scorecards</strong>: Analyze transaction history to predict future behaviour.</li><li><strong>Collection Scorecards</strong>: Assess repayment likelihood for defaulted loans, optimizing collection strategies.</li></ul><h3>Key Considerations in Credit Scorecard Development</h3><h4>Transparency and Process</h4><p>Transparency ensures fairness, accountability, and regulatory compliance. Interpretable models build trust and facilitate effective monitoring.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ure5jRwBCkvftmM208lng.png" /></figure><h4><strong>Data Gathering and Preparation</strong></h4><p>Quality data is critical for reliable models. Key focus areas include:</p><ul><li><strong>Data Quality and Sampling</strong><br>Use robust datasets and exclude non-representative accounts (e.g., VIPs or fraud cases). Select a sampling period that captures diverse repayment patterns.</li><li><strong>Data Cleaning</strong><br>Address missing values through imputation or exclusion, and neutralize outliers by grouping them appropriately. Ensure the sample mirrors portfolio characteristics to avoid biases.</li></ul><h4>Cut-off Selection</h4><p>The cut-off score classifies borrowers as “good” or “bad”. It should balance profitability with risk while adhering to regulatory guidelines. Regular back-testing ensures its relevance and effectiveness.</p><h4><strong>Model Development and Validation</strong></h4><ul><li><strong>Model Development<br></strong>Logistic regression is the most widely used technique for credit scorecard development due to its simplicity, interpretability, and compliance with regulatory standards. Machine learning methods, such as decision trees, random forests, or gradient boosting, on the other hand, can capture complex and nonlinear relationships in data. While these methods may improve accuracy, they often lack the interpretability needed in regulated environments.<br>Weight of Evidence (WoE) transformations are commonly applied to categorical and numerical variables to improve interpretability. This ensures a monotonic relationship between predictors and the target variable (e.g., default vs. non-default). Feature engineering, addressing issues like multicollinearity and missing values, is critical for creating robust models.</li><li><strong>Model Validation<br></strong>Validation is essential to ensure the model’s robustness and performance. Metrics such as the Gini coefficient and the Area Under the Receiver Operating Characteristic Curve (AUC-ROC) assess the model’s discriminatory power. Calibration metrics, such as the Brier score, ensure the predicted probabilities align with actual outcomes.<br>Back-testing involves evaluating the model on holdout datasets or out-of-time samples to confirm its generalizability. Stability tests monitor the model’s performance over time, ensuring it remains reliable under changing conditions. Performance should also be evaluated across different customer segments to identify biases and ensure consistency across sub-populations.</li><li><strong>Ethical, Regulatory and Business Considerations<br></strong>Adherence to regulatory frameworks, such as Basel guidelines or GDPR, is critical throughout the model development process. These regulations emphasize transparency, fairness, and data protection.<br>The model should also align with business objectives, such as minimizing default rates, optimizing credit limits, and maximizing portfolio profitability. Regulatory compliance and alignment with business goals ensure the scorecard is both effective and sustainable.</li></ul><h4><strong>Scorecard Monitoring</strong></h4><p>The scorecard should be deployed with a strong monitoring framework in place, allowing for regular performance tracking and timely adjustments to address changes in population behaviour, regulatory requirements, or business objectives.</p><h3>Conclusion</h3><p>Credit scorecards are indispensable tools for modern risk management, combining statistical rigour with practical applications. This theoretical foundation is just the beginning. In<strong> </strong><a href="https://medium.com/@fabiodigiovanni97/mastering-credit-scorecard-development-part-2-from-data-to-risk-driven-insights-f21cf5ae667a"><strong>Part 2</strong></a>, we’ll bring these concepts to life by implementing a credit scorecard in Python, covering data preprocessing, model building, and evaluation. Stay tuned for a hands-on exploration of credit scorecard development!</p><h3>Let’s Connect!</h3><p>If you enjoyed this article and want to dive deeper into credit risk management, follow me on <a href="https://www.linkedin.com/in/fabio-di-giovanni/">LinkedIn</a>. I’d love to connect and continue the conversation!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1de33a66c2fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reinventing Backtesting: Tackling Correlated Data in Financial Models]]></title>
            <link>https://medium.com/@fabiodigiovanni97/reinventing-backtesting-tackling-correlated-data-in-financial-models-68175b516b45?source=rss-44319ea4bb38------2</link>
            <guid isPermaLink="false">https://medium.com/p/68175b516b45</guid>
            <category><![CDATA[correlation]]></category>
            <category><![CDATA[backtesting]]></category>
            <category><![CDATA[finance-and-banking]]></category>
            <category><![CDATA[credit-risk-management]]></category>
            <category><![CDATA[risk-management]]></category>
            <dc:creator><![CDATA[Fabio Di Giovanni]]></dc:creator>
            <pubDate>Sun, 08 Dec 2024 17:36:53 GMT</pubDate>
            <atom:updated>2024-12-08T17:36:53.350Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ddc1OvuUj52a9eIxN3Jxpg.jpeg" /></figure><p>Backtesting is a cornerstone of financial model validation, ensuring that predictive models align with real-world market dynamics. However, when working with correlated data — a frequent occurrence in applications like counterparty credit risk (CCR) and other long-horizon scenarios — standard statistical methods face significant challenges. This article introduces a transformative technique for decorrelating data using Cholesky decomposition, paving the way for robust and scalable backtesting in complex financial systems.</p><h3>The Challenge: Correlated Samples and Reduced Test Power</h3><p>Correlated samples arise naturally in financial time series due to autocorrelations (e.g., in daily returns aggregated over multiple days) or cross-correlations (e.g., across multiple assets). Common statistical tests such as exceedance counting or the chi-squared test assume independence of samples. Correlation distorts their null distributions, often creating long tails and reducing the ability of tests to distinguish between valid and invalid models.</p><p><strong>Existing Solutions</strong></p><ol><li><strong>Monte Carlo Null Distributions</strong>: Simulate correlated data under the null hypothesis to compute test statistics. This accounts for correlation but can lead to long-tailed distributions and reduced power.</li><li><strong>Filtered Correlation</strong>: Remove correlated samples to restore independence. While effective, this sacrifices data, which is especially problematic for long-horizon backtests.</li></ol><h3>The Solution: Decorrelation via Cholesky Decomposition</h3><p>The innovative approach involves preprocessing the data to remove correlations before applying standard statistical tests. By separating decorrelation from hypothesis testing, this method preserves the integrity of established tests and enhances their discriminatory power.</p><h4>Step-by-Step Decorrelation Process</h4><p>To process the data for decorrelation, start by computing the <strong>correlation matrix<em> C</em></strong> for the data under the null hypothesis. This matrix represents the relationships between all variables, capturing the dependencies that need to be addressed.</p><p>Next, perform the <strong>Cholesky decomposition</strong> of the correlation matrix. This step decomposes <strong><em>C</em></strong> into the product of a lower triangular matrix <strong><em>L</em></strong> (called the Cholesky root) and its transpose. Mathematically, this can be expressed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*PlEGVRVsUWu3Y2l9ufQIbQ.png" /></figure><p>where <strong><em>L</em></strong> is the matrix we will use to decorrelate the data.<br>Once <strong><em>L</em></strong> is computed, transform the correlated data <strong><em>X</em></strong> by multiplying it with the inverse of <strong><em>L</em></strong>. The transformed data is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*TjckvIDK2sG27p81bdcjnQ.png" /></figure><p>This transformation effectively removes the correlation present in <strong><em>X</em></strong>, ensuring the data is now independent.</p><p>For cases involving <strong>Probability Integral Transforms (PIT)</strong>, special care must be taken to ensure the transformed values remain within the valid range (e.g., [0, 1] for uniform distributions). This is achieved using the cumulative distribution function (CDF) Φ of a standard normal distribution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*D6XF4Jr1pcDZiF4LLdVE6A.png" /></figure><p>where Φ⁻¹ is the inverse CDF (also known as the quantile function). This step ensures the transformed values are both decorrelated and properly scaled for statistical testing.</p><h3>Numerical Case Study: Gaussian Time Series Returns</h3><h4>Problem Setup</h4><p>We test the volatility of Gaussian returns aggregated over <em>m</em>-day windows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*seF3_3_GjH4hWm-xPBehQg.png" /></figure><ul><li><strong>Null Hypothesis (H₀):</strong> σ ≤ σ₀</li><li><strong>Alternative Hypothesis (H₁):</strong> σ &gt; σ₀</li><li>Data: 250 days, 10-day moving window.</li></ul><h4>Methodology Comparison</h4><ul><li><strong>Filtered Data</strong>: Reduces the sample size to remove correlations.</li><li><strong>Correlated Null Distributions</strong>: Incorporates correlation into test statistics using Monte Carlo simulations.</li><li><strong>Decorrelated Data</strong>: Removes correlation from samples using Cholesky decomposition.</li></ul><h4>Results</h4><ul><li><strong>Power Curves</strong>: The decorrelated approach achieves the highest power, effectively distinguishing between null and alternative hypotheses.</li><li><strong>Null Distributions</strong>: Long-tailed null distributions in the correlated approach reduce test effectiveness, whereas decorrelation yields well-separated distributions, enhancing test reliability.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aj9s_RbuWfVArrgzOcCREg.png" /><figcaption>Figure 1: Gaussian Time Series Returns: Power Curves of Exceedance Count</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6dvhUYpzapU7i4XQClmE2A.png" /><figcaption>Figure 2: Gaussian Time Series Returns: PDFs of Exceedance Count (Null vs. Alt)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wV7079wdxdQA7pmPQNWKKw.png" /><figcaption>Figure 3: Gaussian Time Series Returns: Power Curves of χ²</figcaption></figure><h3>Application to CCR Backtesting</h3><p>Counterparty Credit Risk (CCR) refers to the risk that a counterparty in a financial contract, such as a derivative or loan, may default before the contract matures. This risk is dynamic, as the exposure evolves with market conditions over time. CCR is especially significant in long-term financial instruments where overlapping data windows are common, leading to correlations that complicate statistical backtesting. Accurate CCR backtesting is essential not only for regulatory compliance but also for ensuring the robustness of financial institutions’ risk management systems.</p><h4>The Challenge in Long-Horizon CCR Backtesting</h4><p>In CCR models, backtesting often involves evaluating exposure profiles over periods as long as one year. These extended horizons introduce overlapping data windows, causing high levels of correlation among Probability Integral Transforms (PITs) or other model outputs. Traditional methods, such as filtering correlated samples, discard valuable data, while relying on correlated null distributions risks reduced discriminatory power due to distorted null hypotheses.</p><h4>How Decorrelation Enhances CCR Backtesting</h4><p>By applying Cholesky decomposition, we preprocess PITs to remove both autocorrelations and cross-correlations. This enables robust statistical testing even with small datasets, ensuring accurate validation of CCR models.</p><h4>Case Study: Drift-Free Arithmetic Brownian Motion (ABM)</h4><p>Consider a CCR model that predicts exposure paths using a drift-free arithmetic Brownian motion (ABM) process. Here’s how we apply the decorrelation method to backtest the model:</p><p><strong>Setup:</strong></p><ul><li><strong>Observation Window</strong>: 5 years of historical data with a bi-weekly grid.</li><li><strong>Simulation Horizon</strong>: 1 year, reflecting typical CCR requirements.</li><li><strong>Null Hypothesis</strong>: The model accurately estimates volatility (σ = σ₀).</li></ul><p><strong>Process:</strong></p><ul><li>Simulated exposure paths are transformed into PITs for normalization.</li><li>The correlation structure of these PITs is removed using Cholesky decomposition.</li><li>Statistical tests (e.g., exceedance counting, chi-squared tests) are applied to the decorrelated samples.</li></ul><p><strong>Results:</strong></p><ul><li>The decorrelated approach maintains high discriminatory power, outperforming methods that account for correlation directly.</li><li>It accurately detects both over- and under-estimation of volatility, even with significant overlap in data windows.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wlQdayo1g6jIFyfJFAdMfw.png" /><figcaption>Figure 4: CCR Backtesting</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OjyAShv9OZZ7JJvkbGcy8A.png" /><figcaption>Figure 5: CCR Backtesting</figcaption></figure><h4>Why It Matters</h4><p>CCR models must be validated across long horizons to capture cumulative risks effectively. Traditional backtesting approaches often fail in such scenarios due to correlation-induced distortions or data loss. The decorrelation method provides a solution, enabling rigorous validation without sacrificing data integrity or statistical power. This makes it an indispensable tool for financial institutions striving to meet regulatory requirements and improve the reliability of their risk management frameworks.</p><h3>Long- vs. Short-Horizon Backtesting</h3><p>Short-horizon backtests focus on high-frequency data with near-independence, enabling straightforward statistical tests. However, they miss long-term risks. Long-horizon tests face challenges from overlapping windows and correlations, which distort null distributions. The decorrelation approach aligns short- and long-horizon tests under a unified framework, ensuring robust validation across timescales.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X66l1dD1MTwMeKaF00aYfQ.png" /><figcaption>Figure 6: Probability of rejecting the model</figcaption></figure><h3>Why Cholesky?</h3><p>Cholesky decomposition is favored for its simplicity, efficiency, and strong performance in removing correlation. It transforms the correlation problem into a preprocessing step, allowing the use of standard, well-understood statistical tests.</p><h3>Conclusion</h3><p>Decorrelating samples revolutionizes backtesting by addressing a longstanding challenge in financial model validation. It enhances test power, stabilizes null distributions, and supports multivariate and long-horizon scenarios.</p><h4>Acknowledgement</h4><p>This article builds on the innovative methods introduced by <a href="https://www.linkedin.com/search/results/all/?heroEntityKey=urn%3Ali%3Afsd_profile%3AACoAABoyxCABEgVRxL9qxtn1cJeXugfbrwRfRuA&amp;keywords=Nikolai%20Nowaczyk&amp;origin=ENTITY_SEARCH_HOME_HISTORY&amp;sid=%40dB">Nikolai Nowaczyk</a> and <a href="https://www.linkedin.com/in/piterbarg/">Vladimir Piterbarg</a> in their paper <em>“</em><a href="https://papers.ssrn.com/sol3/papers.cfm?abstract_id=4571812"><em>Backtesting Correlated Quantities</em></a><em>”.</em> Readers interested in a detailed technical exploration are encouraged to consult their original work.</p><h4>Let’s Connect!</h4><p>If you enjoyed this article and would like to dive deeper into similar topics, feel free to follow me on <a href="https://www.linkedin.com/in/fabio-di-giovanni/">LinkedIn</a>. I’d love to connect and continue the conversation!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68175b516b45" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>