0% found this document useful (0 votes)
3 views13 pages

Expert Training Program Python Credit Risk Analytics

The document outlines an Expert Training Program that integrates Python programming with credit risk analytics, structured into four stages: beginner, intermediate, advanced, and expert. Each stage includes theoretical concepts, practical applications, and assessments to reinforce learning, focusing on key credit risk parameters and Python libraries. The curriculum emphasizes hands-on coding exercises and real-world examples to equip learners with the skills needed for effective credit risk management.

Uploaded by

w cw
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views13 pages

Expert Training Program Python Credit Risk Analytics

The document outlines an Expert Training Program that integrates Python programming with credit risk analytics, structured into four stages: beginner, intermediate, advanced, and expert. Each stage includes theoretical concepts, practical applications, and assessments to reinforce learning, focusing on key credit risk parameters and Python libraries. The curriculum emphasizes hands-on coding exercises and real-world examples to equip learners with the skills needed for effective credit risk management.

Uploaded by

w cw
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

# Expert Training Program: Python Programming & Credit Risk Analytics

## Introduction

Financial institutions rely on robust analytics and sound programming skills to


quantify and manage credit-related risks. This course manual is designed to
take you from beginner to expert by blending **Python programming** with
**credit-risk management**. Each stage builds on the previous one, integrating
theory with hands-on coding exercises, real-world examples and
professional-grade projects. The manual is divided into four stages—
**beginner**, **intermediate**, **advanced** and **expert**—with assessment
checkpoints, suggested readings and datasets at each level. A glossary of key
terms and summary cheat-sheets at the end of each stage make the material easy
to review.

### Why integrate Python and credit risk?

Modern credit risk analytics relies heavily on data science and statistical
modelling. Python provides a powerful, open-source ecosystem for data handling,
numerical computing and visualisation, while credit risk management supplies the
domain knowledge needed to build models that meet regulatory standards and
business needs. By learning both in concert, you will be able to:

* Understand and implement core concepts such as the **probability of default


(PD)**, **loss given default (LGD)**, **exposure at default (EAD)** and
**expected loss (EL)**, which are key risk parameters in the Basel regulatory
framework【459323280846832†L200-L210】.
* Use Python libraries (NumPy, pandas, matplotlib, scikit-learn) to build,
evaluate and deploy credit scoring models, stress tests and portfolio-risk
simulations.
* Design end-to-end analysis pipelines that read data from files or APIs, clean
and transform it, fit models and produce business-ready reports.
* Navigate regulations such as Basel II/III, implement logistic regression
models that are transparent to regulators【19683768794443†L40-L69】, and
understand capital calculation requirements【352190975237353†L519-L575】.

The training roadmap below summarises how the two domains are integrated across
the four stages.

## Curriculum Roadmap

| Stage | Python focus | Credit-risk focus | Key assessments & projects |


|---|---|---|---|
| **Beginner** | Programming fundamentals, variables, data types, control
structures, functions, introduction to Jupyter notebooks. | Introduction to
credit risk; definitions of PD, LGD, EAD and EL【459323280846832†L200-L210】;
simple expected-loss calculations【221569822550112†L245-L299】. | Quiz on
programming basics; exercise to compute expected loss in Python; mini-project
analysing a small loan dataset. |
| **Intermediate** | Data structures (lists, tuples, dictionaries, sets), file
I/O, modules, error handling, NumPy, pandas, matplotlib. | Basel II/III
overview; logistic regression models for credit scoring【19683768794443†L40-
L69】; implementing PD models with scikit-learn; evaluation metrics (accuracy,
AUC). | Quiz on data structures and model evaluation; hands-on project building
a logistic regression model on a real dataset; use matplotlib to visualise
results. |
| **Advanced** | Object-oriented programming, modules and packages, data
pipelines, API requests, advanced pandas operations, feature engineering,
scikit-learn workflows. | Advanced credit-risk models (decision trees, random
forests, gradient boosting), time-series PD forecasting, stress testing
【669921987494502†L408-L423】, through-the-cycle vs point-in-time PD
【352190975237353†L519-L575】, introduction to portfolio risk and concentration
risk【458860626409851†L8-L33】. | Assessment on OOP and feature engineering;
project comparing logistic regression and tree-based models; design a simple
stress test and back-test PD forecasts. |
| **Expert** | Writing reusable Python packages, advanced visualisation,
parallel processing, pipelines for model deployment, integration with databases,
documentation and testing. | Portfolio-level risk measurement, credit VaR
【755202400812073†L268-L299】, concentration risk indices【902392304623460†L88-
L115】, credit portfolio simulation, stress-testing scenarios
【669921987494502†L408-L488】, Basel IV capital requirements. | Capstone
project: build a reusable credit-risk analytics pipeline; simulate portfolio
losses and calculate VaR; design and conduct stress tests; final exam. |

Each stage contains concept explanations, practical applications, Python code


examples, exercises, projects, assessment checkpoints, reading suggestions and
cheat-sheets. Progress at your own pace: complete the quizzes and projects
before advancing to ensure mastery of the material.

---

## Stage 1 – Beginner

### 1.1 Python fundamentals

**Concepts & theory**

* **Setting up your environment:** Install Python (preferably via Anaconda) and


set up a virtual environment. Use the Jupyter Notebook or VS Code to run code
interactively.
* **Variables and data types:** Understand integers, floats, strings, booleans
and the `None` type. Python is dynamically typed, meaning you do not declare
variable types explicitly.
* **Operators:** Use arithmetic (`+`, `-`, `*`, `/`, `//`, `%`, `**`),
comparison (`==`, `!=`, `<`, `>`), logical (`and`, `or`, `not`) and assignment
(`=`, `+=`, `-=`, etc.) operators.
* **Control structures:** Use `if/elif/else` statements for conditional logic
and `for`/`while` loops for iteration. Understand how to break out of loops
(`break`) or skip iterations (`continue`).
* **Functions:** Define reusable code blocks with `def`. Use parameters and
return values to make functions flexible. Understand default arguments and
keyword arguments.
* **Input/Output:** Use `input()` to read from the keyboard and `print()` to
display output. Convert strings to numbers with `int()` or `float()`.

**Practical applications**

1. *Simple interest calculator:* Write a program that reads principal, annual


interest rate and time from the user and calculates simple interest. Use
functions to encapsulate the calculation.
2. *Loan amortisation table:* Write a program that calculates monthly payments
on a loan and prints a schedule showing interest and principal components for
each period.
3. *Control-flow challenge:* Given a list of credit ratings
(`['AAA','BB','CCC',…]`), write a loop that counts how many are investment grade
(BBB or higher) and how many are speculative grade.

**Real-world example**

Credit risk quantification begins with the **expected loss (EL)** formula.
Expected loss is calculated as the product of the probability of default, loss
given default and exposure at default【459323280846832†L200-L210】. LGD is
defined as the average economic loss per dollar of exposure the bank expects if
the borrower defaults【352190975237353†L569-L575】, and EAD is the bank’s
estimate of the amount owed at the time of default【352190975237353†L593-L611】.
For example, a bank may estimate that a portfolio of similar commercial loans
has a 2 % probability of default, a loss given default of 40 % and an exposure
at default of $10 million. The expected loss is then:

\[EL = PD \times LGD \times EAD = 0.02 \times 0.40 \times 10\,000\,000 =
80\,000.\]

This means the bank expects to lose $80 000 annually on average. The chart
below illustrates the components of expected loss. Each bar shows one component
and the combined result.

![Expected loss components](expected_loss_components.png)

**Hands-on Python exercise**

```python
def expected_loss(pd: float, lgd: float, ead: float) -> float:
"""Compute expected loss given probability of default (pd), loss given
default (lgd) and exposure at default (ead).

Args:
pd: probability of default, as a decimal (e.g. 0.02 for 2 %).
lgd: loss given default, as a decimal (e.g. 0.4 for 40 %).
ead: exposure at default (monetary units).

Returns:
The expected loss.
"""
return pd * lgd * ead

# Example usage
el = expected_loss(pd=0.02, lgd=0.4, ead=10_000_000)
print(f"Expected loss: ${el:,.2f}")
```

Running this code prints `Expected loss: $80,000.00`, matching the manual
calculation.

**Assessment checkpoint – Stage 1**

1. What is the probability of default (PD)?


**Answer:** PD is the likelihood that a borrower will be unable or unwilling
to repay its debt in full or on time【459323280846832†L217-L223】.
2. How is loss given default (LGD) defined under Basel II?
**Answer:** LGD is the bank’s empirically based estimate of the average
economic loss per dollar of exposure expected if the obligor defaults during
economic downturn conditions【352190975237353†L569-L575】.
3. Write a Python function that returns the larger of two numbers without using
the built-in `max()` function.
4. Explain the difference between a `for` loop and a `while` loop. Provide an
example where a `while` loop is more appropriate.
5. Using the expected loss function above, compute the expected loss when
PD = 5 %, LGD = 50 % and EAD = $500 000.

**Suggested reading & datasets**

* **Definitions and expected loss:**


* Investopedia’s article on loss given default explains the concept and
provides formulas for calculating LGD and how it relates to expected loss
【221569822550112†L245-L299】.
* Corporate Finance Institute’s guide to expected loss shows how PD, LGD and
EAD combine to produce expected losses【924069482911967†L556-L572】.
* **Datasets:**
* The **UCI German Credit Data** contains information about 1 000 borrowers
and whether they defaulted; it is widely used for teaching credit scoring.
* **Kaggle’s Credit Card Default Dataset** provides demographic and financial
information for 30 000 consumers along with a default indicator.

**Cheat-sheet: Stage 1**

* **Expected loss:** \(EL = PD \times LGD \times EAD\)【924069482911967†L556-


L571】.
* **PD definition:** likelihood that a borrower will not be able to meet debt
obligations【459323280846832†L217-L223】.
* **LGD definition:** bank’s best estimate of the average loss per dollar of
exposure if default occurs during economic downturn conditions
【352190975237353†L569-L575】.
* **EAD definition:** the bank’s best estimate of the amount owed at the time of
default【352190975237353†L593-L611】.
* **Simple Python constructs:** variables, operators, control flow, functions,
input/output.

---

## Stage 2 – Intermediate

### 2.1 Python data structures and libraries

**Concepts & theory**

* **Data structures:**
* **Lists** (ordered, mutable sequences) allow appending, popping and
iterating over values. Use list comprehensions to create lists concisely.
* **Tuples** are immutable sequences; they can be used as keys in dictionaries
and are often used to return multiple values from a function.
* **Dictionaries** store key–value pairs; they are ideal for counting
categories (e.g., counts of credit ratings) or mapping variable names to values.
* **Sets** store unique items and support mathematical set operations (union,
intersection).
* **File I/O:** Open files using `with open('[Link]', 'r') as f:` to ensure
proper cleanup. Use the built-in `csv` module for simple CSV reading or pandas
for more complex tasks.
* **Modules and packages:** Organise code into reusable modules (`.py` files)
and packages (folders with an `__init__.py`). Use `import` to bring functions
and classes into scope.
* **Error handling:** Use `try`–`except` to catch exceptions, and `raise` to
signal errors. Always handle potential exceptions when reading files or
converting data types.
* **NumPy and pandas:**
* NumPy provides multidimensional arrays, vectorised operations and linear
algebra routines.
* pandas builds on NumPy and offers data structures (`Series` and `DataFrame`)
for labelled data, along with powerful data manipulation methods (grouping,
merging, pivoting).
* **Matplotlib:** Create line plots, bar charts, histograms and scatter plots.
Use `[Link]()` and `[Link]()` to arrange multiple plots. Customise
axes labels, titles and legends.

**Practical applications**

1. *Reading loan data:* Use pandas to read a CSV containing loan information
(`loan_id`, `amount`, `interest_rate`, `term`, `status`). Compute descriptive
statistics, such as the average interest rate and distribution of loan statuses.
2. *Feature engineering:* Create a new column `installment` that calculates
monthly payments using the amortisation formula. Categorise loans into risk
buckets based on debt-to-income ratios using `[Link]()`.
3. *Visualisation:* Plot histograms of credit scores, box plots of LGD by
collateral type and line plots showing PD over time.
4. *Modules:* Write a module `loan_utils.py` containing helper functions (e.g.,
`calculate_installment()`, `expected_loss()`), then import and use them in your
notebook.

### 2.2 Basel frameworks and logistic regression models

**Concepts & theory**

* **Basel II/III highlights:** Basel II introduced internal ratings-based (IRB)


approaches where banks estimate PD, LGD and EAD for each exposure. PD is
defined as the bank’s best estimate of the long-run average one-year default
rate for an obligor【352190975237353†L519-L531】, LGD is the average economic
loss per dollar of exposure during downturn conditions【352190975237353†L569-
L575】 and EAD is the bank’s estimate of the outstanding amount at default
【352190975237353†L593-L611】. These parameters feed into regulatory capital
calculations.
* **Logistic regression:** Logistic regression is a widely used classification
algorithm that predicts the probability of a binary outcome—such as whether a
customer will default on a loan【19683768794443†L40-L69】. It applies a
**logit** function to a linear combination of input variables; the result is
constrained to the 0–1 range, representing a probability. Logistic regression
is favoured in credit-risk modelling because of its transparency and
interpretability, which regulators value【19683768794443†L40-L53】.
* **Model equation:** For predictors \(x_1, x_2, \dots, x_p\) and coefficients \
(\beta_0, \dots, \beta_p\), logistic regression models the log-odds of default
as

\[\log\left(\frac{\Pr(Y=1)}{1-\Pr(Y=1)}\right) = \beta_0 + \beta_1 x_1 + \dots


+ \beta_p x_p.\]

The probability of default is then \(\Pr(Y=1) = \frac{1}{1 + e^{-(\beta_0 +


\sum\beta_i x_i)}}\).

* **Model training:** Split data into training and test sets; preprocess
variables (handle missing values, scale numeric features, encode categorical
variables); fit the logistic regression model using
`sklearn.linear_model.LogisticRegression`. Evaluate performance using metrics
such as **accuracy**, **precision**, **recall**, **F1 score** and **area under
the ROC curve (AUC)**. Use cross-validation to avoid overfitting.
* **Scorecards:** Credit scorecards transform logistic regression outputs into a
points-based system. Common techniques include weight of evidence (WOE)
encoding and scaling probabilities into points.

**Real-world example**

Suppose we have a dataset of consumer loans containing features such as credit


score, annual income, debt-to-income ratio and default indicator. We want to
build a logistic regression model to estimate the probability of default. The
following code outlines the process:

```python
import pandas as pd
from sklearn.model_selection import train_test_split
from [Link] import StandardScaler
from [Link] import roc_auc_score, confusion_matrix
from sklearn.linear_model import LogisticRegression
# 1. Load the data
df = pd.read_csv('credit_data.csv')

# 2. Preprocess
X = df[['credit_score', 'annual_income', 'dti']]
y = df['default']

# Handle missing values (simple example)


X = [Link]([Link]())

# Standardise numeric features


scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# 3. Split into train and test sets


X_train, X_test, y_train, y_test = train_test_split(
X_scaled, y, test_size=0.3, random_state=42
)

# 4. Fit logistic regression


model = LogisticRegression(max_iter=1000)
[Link](X_train, y_train)

# 5. Evaluate
pred_probs = model.predict_proba(X_test)[:, 1]
auc = roc_auc_score(y_test, pred_probs)
print(f"AUC: {auc:.3f}")

# Confusion matrix at 0.5 threshold


y_pred = (pred_probs >= 0.5).astype(int)
print(confusion_matrix(y_test, y_pred))
```

Use matplotlib to plot the ROC curve and a histogram of predicted probabilities.
The logistic function’s shape is visualised below: an S-shaped curve that maps
linear scores to probabilities.

![Logistic function](logistic_curve.png)

**Assessment checkpoint – Stage 2**

1. Under Basel II, what is the minimum permissible PD for non-sovereign


exposures?
**Answer:** 0.03 %【352190975237353†L552-L555】.
2. Explain why logistic regression is preferred over more complex
machine-learning models in many regulatory credit-risk applications
【19683768794443†L40-L69】.
3. Using pandas, write code to read a CSV of loan data, compute the mean loan
amount by grade (e.g. grade A, B, C) and create a bar chart.
4. Describe the difference between accuracy and AUC when evaluating
classification models.
5. What are three steps involved in preprocessing data before fitting a logistic
regression model?

**Suggested reading & datasets**

* **Basel frameworks:** The Federal Reserve’s Basel II technical overview


describes how banks estimate PD, LGD and EAD for each exposure
【352190975237353†L519-L611】. Investopedia’s article on loss given default
explains the relationship between LGD, PD and EAD【221569822550112†L245-L299】.
The corporate finance article shows how these parameters combine to compute
expected loss【924069482911967†L556-L572】.
* **Logistic regression and credit scoring:** 2nd Order Solutions’ article
“Logistic Regression in the Credit Risk Industry” explains why logistic
regression is widely used, emphasising its transparency and ability to interpret
predictor effects【19683768794443†L40-L69】. It describes the importance of
monotonicity in regulatory contexts【19683768794443†L79-L106】.
* **Datasets:** In addition to the datasets suggested in Stage 1, use the
**LendingClub Loan Data** or **Home Credit Default Risk** dataset on Kaggle,
both of which provide detailed loan and borrower information.

**Cheat-sheet: Stage 2**

* **Logistic regression formula:** \(\Pr(Y=1) = 1/(1+e^{-z})\), where \(z =


\beta_0 + \sum\beta_i x_i\).
* **PD estimation:** For each rating grade or retail segment, PD is the long-run
average one-year default rate【352190975237353†L519-L537】.
* **LGD estimation:** Average loss per dollar of exposure under downturn
conditions【352190975237353†L569-L575】.
* **EAD estimation:** Best estimate of the amount owed at default, including
expected future draws for lines of credit【352190975237353†L593-L611】.
* **Model evaluation metrics:** Accuracy, precision, recall, F1 score, AUC;
confusion matrix.
* **Python libraries:** `pandas` for data manipulation, `NumPy` for numerical
operations, `matplotlib` for visualisation, `scikit-learn` for modelling.

---

## Stage 3 – Advanced

### 3.1 Advanced Python and feature engineering

**Concepts & theory**

* **Object-oriented programming (OOP):** Define classes to model entities such


as `Loan` or `Portfolio`. Use attributes to store data and methods to compute
values (e.g., `Loan.expected_loss()`). Understand inheritance (e.g.,
`SecuredLoan` subclass of `Loan` with additional collateral attributes) and
polymorphism.
* **Modules and packages:** Create a package structure (e.g., `creditrisk/`)
containing modules for data loading, preprocessing, modelling and evaluation.
Write `__init__.py` to expose high-level functions.
* **Data pipelines:** Use scikit-learn’s `Pipeline` and `ColumnTransformer` to
chain preprocessing steps (imputation, scaling, encoding) and models. Pipelines
help avoid data leakage and simplify cross-validation.
* **APIs and web requests:** Use the `requests` library to fetch data from web
APIs (e.g., retrieving economic indicators for stress testing). Handle JSON
responses with `[Link]()` and convert them into pandas DataFrames.
* **Feature engineering:** Develop domain-specific features such as credit
utilisation ratios, payment history indicators, vintage effects and
macroeconomic variables. Use grouping, rolling averages and interaction terms.
* **Handling class imbalance:** Credit default datasets often have a minority of
default events. Use techniques such as **SMOTE** (synthetic minority
oversampling), **undersampling** or **class weighting** to improve model
performance.

**Practical applications**

1. *Credit-risk OOP:* Create a `Loan` class with attributes (`principal`,


`interest_rate`, `term`, `pd`, `lgd`, `ead`) and methods `monthly_payment()` and
`expected_loss()`. Write a `Portfolio` class that stores a list of loans and
computes aggregate expected loss and capital requirements.
2. *Pipelines:* Build a scikit-learn pipeline that imputes missing values,
scales numeric variables and fits a random forest classifier. Use
`GridSearchCV` to tune hyperparameters.
3. *APIs:* Retrieve unemployment rate and GDP growth data from an economic data
API (e.g., FRED). Merge these macro variables with loan data to incorporate
economic conditions into your PD model.
4. *Feature selection:* Use mutual information or recursive feature elimination
to select variables that contribute most to the predictive power.

### 3.2 Advanced credit-risk models and stress testing

**Concepts & theory**

* **Decision trees and ensemble methods:** Decision trees partition the feature
space into regions and assign predictions based on majority class. Random
forests aggregate many decision trees to reduce variance, while gradient
boosting combines weak learners sequentially to minimise errors. These models
can capture nonlinear relationships and interactions.
* **Time-series PD forecasting:** In retail portfolios, PD may vary over time
due to economic cycles. Use rolling windows to compute delinquency rates and
fit time-series models (e.g., ARIMA, VAR, or machine-learning models) to
forecast PD. The GARP white paper on economic time-series-based risk models
discusses converting point-in-time estimates to through-the-cycle estimates and
de-trending macroeconomic series【514404200880202†L54-L73】.
* **Stress testing:** Stress testing is a forward-looking quantitative
evaluation of scenarios that could impact a bank’s financial condition
【669921987494502†L408-L419】. Stress tests simulate adverse economic events
(e.g., decline in property prices or rise in unemployment) and assess the impact
on portfolio losses and capital adequacy. Banks may apply simple sensitivity
analyses (e.g., increasing default rates by a fixed factor), scenario analyses
(multiple variables changing concurrently) or reverse stress tests (finding the
scenario that would breach capital ratios)【669921987494502†L433-L479】.
* **Through-the-cycle vs point-in-time PD:** Point-in-time PD estimates reflect
current economic conditions, while through-the-cycle PDs smooth out cyclical
fluctuations and represent the long-run average default probability
【352190975237353†L519-L575】. Basel II capital formulas require long-run
average PDs, but risk managers often use point-in-time estimates for internal
risk management. Methods such as variable scalar and structural models adjust
point-in-time estimates to through-the-cycle estimates【514404200880202†L54-
L73】.
* **Portfolio risk and concentration risk:** Portfolio risk arises from holding
multiple exposures; concentration risk is the additional risk from high exposure
to one obligor or group of correlated obligors. A portfolio approach emphasises
the importance of default correlation: simultaneous defaults can produce severe
losses【458860626409851†L8-L33】. The MathWorks article defines concentration
risk as the potential for a significant loss when exposures move together in an
unfavourable direction【902392304623460†L88-L92】. Techniques for measuring
concentration include concentration indices (Herfindahl–Hirschman index, Gini
coefficient) and stress tests【902392304623460†L104-L116】.

**Real-world example**

*Stress test on a mortgage portfolio:* Suppose a community bank wants to


evaluate its mortgage portfolio under a severe downturn scenario. The bank
applies stressed portfolio loss rates, increasing default probabilities and
LGDs. According to the FDIC guidance, stress tests should reflect assumptions
about adverse external events (e.g., falling real-estate prices) and help assess
whether financial and operational resources are sufficient to withstand a
downturn【669921987494502†L408-L419】. The bank can estimate stressed loss
rates based on historical recession data and apply them to current balances
【669921987494502†L455-L499】. It then projects earnings and capital under
moderate and severe scenarios to evaluate capital adequacy.
**Hands-on project**

1. *Tree-based models:* Using a default dataset, build and compare a logistic


regression, decision tree and random forest. For each model, compute AUC,
precision, recall and confusion matrix. Plot feature importances for the tree
models.
2. *Stress test simulation:* Create a simple mortgage portfolio with 1 000
loans, each characterised by PD, LGD and EAD. Increase PDs by 50 % and LGDs by
25 % to simulate recession conditions. Compute the stressed expected loss and
compare it with the baseline. Extend the simulation by correlating defaults:
when one borrower defaults, increase the PD of correlated borrowers.
3. *Through-the-cycle adjustment:* Use macroeconomic variables (e.g. GDP growth)
to decompose point-in-time PDs into trend and cyclical components. Apply a
smoothing filter (e.g. Hodrick–Prescott filter) to extract the trend and derive
a through-the-cycle PD estimate.

**Assessment checkpoint – Stage 3**

1. Explain the difference between point-in-time and through-the-cycle PD


estimates【352190975237353†L519-L575】.
2. Describe two types of stress tests mentioned in FDIC guidance
【669921987494502†L433-L479】 and their purpose.
3. Implement a scikit-learn pipeline that imputes missing values, scales numeric
features and fits a gradient boosting classifier. Evaluate it using 5-fold
cross-validation and report the average AUC.
4. Why is concentration risk particularly dangerous in credit portfolios?
**Answer:** Concentration risk increases portfolio risk because exposures to
correlated obligors may default simultaneously; default correlations produce
highly skewed loss distributions【458860626409851†L8-L33】. Diversification
mitigates this risk.
5. For a portfolio of 500 loans with identical PD = 3 %, LGD = 35 % and
EAD = $200 000, calculate the baseline expected loss and the expected loss if
PDs rise by 40 % in a stress scenario.

**Suggested reading & datasets**

* **Stress testing:** The FDIC article “Stress Testing Credit Risk at Community
Banks” explains what stress testing is, emphasising that it is a forward-looking
evaluation of stress scenarios【669921987494502†L408-L419】 and provides examples
of stress-testing methodologies【669921987494502†L433-L479】.
* **Concentration risk:** MathWorks’ concentration risk article defines
concentration risk and suggests techniques to measure it【902392304623460†L88-
L115】. The National Institute of Bank Management’s lecture notes on portfolio
credit risk describe how concentration risk arises from correlated defaults and
emphasise the role of default correlation【458860626409851†L8-L33】.
* **Economic time-series-based models:** The GARP white paper discusses methods
for converting point-in-time risk parameters into through-the-cycle estimates
using macroeconomic time series【514404200880202†L54-L73】.
* **Datasets:** Use historical mortgage performance data (e.g., the Freddie Mac
Single-Family Loan-Level Dataset) or corporate default data (e.g., Moody’s
Default & Recovery Database). Macroeconomic series can be downloaded from the
Federal Reserve Economic Data (FRED) API.

**Cheat-sheet: Stage 3**

* **Stress testing definition:** Forward-looking quantitative evaluation of


adverse scenarios affecting a bank’s financial condition and capital
【669921987494502†L408-L419】.
* **Types of stress tests:** Sensitivity analysis, scenario analysis and reverse
stress testing【669921987494502†L433-L479】.
* **Portfolio risk:** Risk arising from multiple exposures; concentration risk
is additional risk from high exposure to correlated obligors
【458860626409851†L8-L33】.
* **Concentration risk indices:** Herfindahl–Hirschman index, Gini coefficient,
Theil entropy index【902392304623460†L104-L116】.
* **Through-the-cycle adjustment methods:** Variable scalar, structural model
and hybrid approaches【514404200880202†L54-L73】.
* **OOP patterns:** Classes encapsulate data and behaviour; use inheritance and
composition to build complex systems; create reusable modules and pipelines.

---

## Stage 4 – Expert

### 4.1 Advanced Python and reproducible analytics

**Concepts & theory**

* **Reusable packages:** Organise your code into a Python package (e.g.,


`creditrisk`). Use `[Link]`/`[Link]` to define dependencies and
packaging information. Write clear docstrings and unit tests using `pytest`.
Provide example Jupyter notebooks demonstrating package usage.
* **Parallel and distributed computing:** Use libraries like `joblib` or `dask`
to parallelise model training and simulation workloads. For example, run
bootstrap or Monte-Carlo simulations in parallel to speed up VaR computations.
* **Database integration:** Use `SQLAlchemy` or `pandas`’ `read_sql()` to read
from and write to relational databases. Store model parameters and results in a
database for reproducibility.
* **Pipeline automation:** Automate data extraction, transformation, modelling
and reporting with tools like Airflow or Prefect. Use scheduling and dependency
management to ensure pipelines run reliably.
* **Documentation and deployment:** Use `sphinx` to generate documentation from
docstrings. Package your models as APIs using `FastAPI` or `Flask` so that
other teams can query PD estimates or stress-test results.

### 4.2 Portfolio-level risk, VaR and concentration risk

**Concepts & theory**

* **Value at Risk (VaR):** VaR quantifies the extent of possible losses within a
firm, portfolio or position over a specified time frame【755202400812073†L268-
L299】. It measures the potential loss amount, the probability of occurrence
and the horizon. Common methods for computing VaR include the historical,
variance–covariance and Monte-Carlo approaches【755202400812073†L315-L344】.
* **Credit VaR:** Credit VaR extends VaR to credit portfolios, measuring the
maximum potential credit loss over a specified horizon at a given confidence
level. Unlike expected loss, credit VaR focuses on unexpected losses (the tail
of the loss distribution). To compute credit VaR, one typically simulates
correlated default events, assigns losses to each default and takes the quantile
of the loss distribution.
* **Concentration risk management:** High exposures to one obligor, industry,
geography or product can lead to large losses if conditions deteriorate.
Concentration risk is the potential for a significant loss when a group of
exposures moves together unfavourably【902392304623460†L88-L92】. Risk managers
set concentration limits, use diversification strategies and apply stress tests
to monitor and control concentration risk.
* **Credit portfolio simulation:** Build a model that simulates default events
using Bernoulli trials with specified PDs and correlations (e.g., using a
Gaussian copula). For each simulation, compute portfolio loss as \(\sum EAD_i
\times LGD_i \times \mathbb{1}_{\{\text{default}_i\}}\). Repeat the simulation
many times to obtain a loss distribution, then calculate expected loss,
unexpected loss and VaR.
* **Basel IV highlights:** Basel IV (often called the “final Basel III reforms”)
introduces more risk-sensitive capital requirements, emphasises output floors
and revises credit-risk weights. Banks must ensure models are robust and
transparent, with proper governance.

**Real-world example**

*Credit portfolio simulation and VaR calculation:* Consider a portfolio of 2 000


loans across various industries. Each loan has PD, LGD and EAD parameters. To
compute credit VaR at the 99 % confidence level over a one-year horizon:

1. **Simulate default events:** Use a copula to model default correlation.


Sample correlated standard normal variables, transform them to default
indicators by comparing with PD thresholds.
2. **Calculate losses:** For each simulation, compute total loss as \(\sum_i
PD_i \times LGD_i \times EAD_i\) for defaulted loans.
3. **Compute loss distribution:** After many simulations (e.g., 10 000), sort
the losses. The 99th percentile is the credit VaR.
4. **Compare with expected loss:** The difference between credit VaR and
expected loss is the unexpected loss. This informs the level of capital the
bank should hold.

**Hands-on capstone project**

1. **Build a reusable credit-risk analytics package:** Organise your functions


and classes into a package. Include modules for data ingestion, feature
engineering, modelling (logistic regression, random forest, gradient boosting),
portfolio simulation and stress testing. Write unit tests and documentation.
2. **Simulate a credit portfolio:** Using your package, simulate defaults for a
synthetic portfolio of 2 000 loans. Estimate expected loss, credit VaR at 95 %
and 99 % confidence levels, and concentration indices. Plot the loss
distribution and mark the VaR thresholds.
3. **Stress test:** Design a macroeconomic stress scenario (e.g., GDP falls by
3 %, unemployment rises by 2 %). Increase PDs and LGDs accordingly and
recompute expected loss and VaR. Assess whether capital buffers are sufficient.
4. **Reporting:** Generate a report summarising the portfolio composition, model
performance, risk measures and recommended actions. Provide interactive charts
using `matplotlib` or `plotly`.

**Assessment checkpoint – Stage 4**

1. Define Value at Risk and explain how it differs from expected loss
【755202400812073†L268-L299】.
2. Outline the steps for simulating credit VaR for a portfolio of loans.
3. Describe at least two methods for managing concentration risk
【902392304623460†L104-L115】.
4. Explain why unexpected loss matters for capital planning.
5. Discuss the key differences between Basel III and the “final Basel III
reforms” (often called Basel IV).

**Suggested reading & resources**

* **VaR:** Investopedia’s article on value at risk explains the concept, methods


of computation and advantages and disadvantages【755202400812073†L268-L344】.
* **Concentration risk:** MathWorks’ explanation of concentration risk and tools
for measuring it【902392304623460†L88-L115】. The portfolio risk lecture notes
illustrate how default correlation drives concentration risk
【458860626409851†L8-L33】.
* **Credit portfolio simulation:** Look for research on the CreditMetrics
methodology and copula-based credit portfolio models. The open-source `pyfolio`
and `creditrisk` packages provide examples.
* **Basel IV regulations:** Review official Basel Committee publications for the
latest regulatory requirements.

**Cheat-sheet: Stage 4**

* **Value at Risk:** Quantifies the potential loss at a specified confidence


level over a given horizon【755202400812073†L268-L299】.
* **Credit VaR:** Maximum potential credit loss over a horizon at a confidence
level; focuses on unexpected loss.
* **Concentration risk:** Risk of large losses when correlated exposures default
simultaneously【902392304623460†L88-L92】; measure using concentration indices
and stress tests.
* **Portfolio simulation:** Use copulas to model default correlations; compute
loss distribution; VaR is the appropriate percentile of the distribution.
* **Basel IV:** Strengthens capital floors and revises risk weights; emphasises
simplicity and comparability of bank capital requirements.

---

## Glossary of Key Terms

* **Probability of default (PD):** The likelihood that a borrower will be unable


or unwilling to repay its debt obligations over a one-year horizon
【459323280846832†L217-L223】. In Basel II, PD is estimated as the long-run
average default rate for an obligor or segment【352190975237353†L519-L537】.
* **Loss given default (LGD):** The average economic loss per dollar of exposure
that the bank expects if the borrower defaults during economic downturn
conditions【352190975237353†L569-L575】. LGD can be expressed as a percentage
of the exposure or a monetary amount【221569822550112†L245-L253】.
* **Exposure at default (EAD):** The bank’s best estimate of the amount owed by
the borrower at the time of default, including undrawn commitments and accrued
interest【352190975237353†L593-L611】.
* **Expected loss (EL):** The average amount a bank expects to lose on an
exposure or portfolio, calculated as \(EL = PD \times LGD \times EAD\)
【924069482911967†L556-L572】.
* **Through-the-cycle (TTC) PD:** A PD estimate that smooths out cyclical
fluctuations and reflects the long-run average default probability
【352190975237353†L519-L575】. Contrasts with point-in-time PD.
* **Point-in-time (PIT) PD:** A PD estimate that reflects current economic
conditions and borrower characteristics, often used for internal risk management
and pricing.
* **Basel Accords:** A series of international banking regulations (Basel I, II,
III, IV) published by the Basel Committee on Banking Supervision. They set
minimum capital requirements and define risk-measurement approaches, including
IRB approaches for credit risk.
* **Credit scorecard:** A model that assigns points based on borrower attributes
to produce a credit score. Often built using logistic regression and weight of
evidence encoding.
* **Stress testing:** A forward-looking evaluation of how an institution’s
financial condition and capital would be affected by adverse scenarios
【669921987494502†L408-L419】. Includes sensitivity analysis, scenario analysis
and reverse stress tests【669921987494502†L433-L479】.
* **Concentration risk:** The potential for a significant loss when exposures
are concentrated in one obligor, industry or geography; arises from correlated
defaults【902392304623460†L88-L92】【458860626409851†L8-L33】.
* **Value at Risk (VaR):** A statistic that quantifies the extent of potential
losses within a portfolio over a specified time frame at a given confidence
level【755202400812073†L268-L299】.
* **Credit VaR:** The maximum potential credit loss (unexpected loss) for a
portfolio at a given confidence level. Differs from expected loss, which
measures the average loss.
---

## Conclusion

By progressing through this training program you will have mastered both the
technical and conceptual foundations necessary to become a credit-risk data
scientist. Starting from programming fundamentals, you learned how to calculate
expected losses, build and evaluate credit scoring models, implement advanced
analytics pipelines and perform stress tests and portfolio simulations. The
integration of Python programming and credit-risk management ensures that you
can not only derive theoretical risk measures but also implement them in
reproducible code that meets regulatory standards. Continue exploring real
datasets, refining your models and staying current with regulatory developments—
credit risk is a dynamic field, and sustained learning is key to professional
growth.

You might also like