Banking Risk Management

30 minintermediate

7. Banking Risk Management

Banks operate in an environment of uncertainty, facing various risks that can threaten their solvency, profitability, and ability to serve their customers. Effective risk management is not optional for banks - it is essential for their survival and for the stability of the financial system. Understanding how banks identify, measure, manage, and mitigate risks is crucial for understanding how banking systems function and how they can fail. Risk management in banking has evolved significantly over time, becoming increasingly sophisticated and quantitative, but the fundamental challenge remains: how to take risks that generate returns while avoiding risks that threaten the bank's existence.

Risk Taxonomy in Banking

Banks face multiple types of risks, each with different characteristics, different measurement challenges, and different management approaches. Understanding the taxonomy of banking risks - how risks are categorized and how they relate to each other - provides the foundation for effective risk management. The major categories of banking risk include credit risk, market risk, operational risk, liquidity risk, and various other risks that banks must manage.

Credit Risk: The Risk of Borrower Default

Credit risk is the risk that borrowers will fail to repay their loans or meet their other obligations. This is perhaps the most fundamental risk that banks face, as lending is a core banking function. Credit risk arises whenever a bank extends credit - whether through loans, credit cards, bonds, or other credit instruments. The bank faces the possibility that the borrower will default, causing the bank to lose some or all of the principal and interest.

Credit risk has several dimensions. Probability of default (PD) measures the likelihood that a borrower will default. Loss given default (LGD) measures the percentage of the exposure that will be lost if default occurs. Exposure at default (EAD) measures the amount that will be outstanding at the time of default. These three components combine to determine expected loss:

EL=PD×LGD×EADEL = PD \times LGD \times EAD

This equation states that expected loss (ELEL) equals the product of probability of default (PDPD), loss given default (LGDLGD), and exposure at default (EADEAD). Banks use this framework to estimate credit losses and to price credit products appropriately.

Credit risk varies significantly across different types of borrowers and different economic conditions. Individual borrowers have different creditworthiness based on their income, assets, credit history, and other factors. Corporate borrowers have different creditworthiness based on their financial condition, business prospects, and industry conditions. Economic conditions affect credit risk across all borrowers, as recessions increase default rates while expansions decrease them.

Credit Risk: The risk that borrowers will fail to repay their obligations, causing losses for lenders. Credit risk is measured using probability of default (PD), loss given default (LGD), and exposure at default (EAD), which combine to determine expected loss.

Banks manage credit risk through several mechanisms. Credit underwriting evaluates borrowers' creditworthiness before extending credit. Credit monitoring tracks borrowers' financial condition and identifies deteriorating credits. Credit limits restrict exposure to individual borrowers or sectors. Collateral and guarantees provide protection against losses. Diversification spreads risk across many borrowers and sectors. These mechanisms work together to control credit risk, though they cannot eliminate it entirely.

Let's visualize credit risk distributions and how banks model expected losses:

Python exercise

#| label: banking-risk-0
#| fig-cap: "Credit Risk Distributions and Expected Loss Modeling"
#| fig-width: 16
#| fig-height: 10
#| echo: false
#| warning: false

# Sandbox metadata (auto-generated from lesson.ts)
# libraries: numpy, matplotlib

import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display

# Set style
plt.style.use('default')
plt.rcParams['figure.facecolor'] = 'white'
plt.rcParams['axes.grid'] = True
plt.rcParams['grid.alpha'] = 0.3
fig, axes = plt.subplots(2, 2, figsize=(16, 10))
fig.suptitle('Credit Risk Distributions and Expected Loss Modeling', 
             fontsize=16, fontweight='bold', y=0.995)

# 1. Probability of Default Distribution
ax1 = axes[0, 0]
# Simulate PD distribution across borrowers (beta distribution for probabilities)
pd_values = np.random.beta(2, 20, 1000) * 0.15  # Most borrowers have low PD
ax1.hist(pd_values, bins=30, color='steelblue', alpha=0.7, edgecolor='black')
ax1.axvline(np.mean(pd_values), color='red', linestyle='--', linewidth=2, 
            label=f'Mean PD: {np.mean(pd_values):.3f}')
ax1.set_xlabel('Probability of Default (PD)', fontsize=11, fontweight='bold')
ax1.set_ylabel('Frequency', fontsize=11, fontweight='bold')
ax1.set_title('Distribution of Probability of Default', fontsize=12, fontweight='bold')
ax1.legend()
ax1.grid(True, alpha=0.3)

# 2. Loss Given Default Distribution
ax2 = axes[0, 1]
# LGD typically follows a beta distribution (0 to 1)
lgd_values = np.random.beta(2, 3, 1000)  # Skewed toward lower losses
ax2.hist(lgd_values, bins=30, color='coral', alpha=0.7, edgecolor='black')
ax2.axvline(np.mean(lgd_values), color='red', linestyle='--', linewidth=2,
            label=f'Mean LGD: {np.mean(lgd_values):.2%}')
ax2.set_xlabel('Loss Given Default (LGD)', fontsize=11, fontweight='bold')
ax2.set_ylabel('Frequency', fontsize=11, fontweight='bold')
ax2.set_title('Distribution of Loss Given Default', fontsize=12, fontweight='bold')
ax2.legend()
ax2.grid(True, alpha=0.3)

# 3. Expected Loss Calculation: EL = PD × LGD × EAD
ax3 = axes[1, 0]
# Simulate portfolio of loans
n_loans = 100
ead_values = np.random.lognormal(10, 0.5, n_loans)  # Exposure amounts
pd_individual = np.random.beta(2, 20, n_loans) * 0.15
lgd_individual = np.random.beta(2, 3, n_loans)
expected_loss = pd_individual * lgd_individual * ead_values

# Sort for visualization
sorted_idx = np.argsort(expected_loss)
sorted_el = expected_loss[sorted_idx]

ax3.bar(range(n_loans), sorted_el, color='mediumseagreen', alpha=0.7, edgecolor='black')
ax3.axhline(np.mean(expected_loss), color='red', linestyle='--', linewidth=2,
            label=f'Mean EL: ${np.mean(expected_loss):,.0f}')
ax3.set_xlabel('Loan (sorted by Expected Loss)', fontsize=11, fontweight='bold')
ax3.set_ylabel('Expected Loss ($)', fontsize=11, fontweight='bold')
ax3.set_title('Expected Loss by Loan: EL = PD × LGD × EAD', fontsize=12, fontweight='bold')
ax3.legend()
ax3.grid(True, alpha=0.3, axis='y')

# 4. Credit Risk Heatmap: PD vs LGD
ax4 = axes[1, 1]
# Create 2D histogram of PD vs LGD
pd_grid = np.random.beta(2, 20, 5000) * 0.15
lgd_grid = np.random.beta(2, 3, 5000)
hist, xedges, yedges = np.histogram2d(pd_grid, lgd_grid, bins=20)
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
im = ax4.imshow(hist.T, origin='lower', extent=extent, aspect='auto', 
                cmap='YlOrRd', interpolation='nearest')
ax4.set_xlabel('Probability of Default (PD)', fontsize=11, fontweight='bold')
ax4.set_ylabel('Loss Given Default (LGD)', fontsize=11, fontweight='bold')
ax4.set_title('Credit Risk Heatmap: PD vs LGD Distribution', fontsize=12, fontweight='bold')
plt.colorbar(im, ax=ax4, label='Frequency')

plt.tight_layout()
display(fig)
plt.close(fig)

Market Risk: The Risk of Price Movements

Market risk is the risk that changes in market prices - interest rates, exchange rates, equity prices, commodity prices - will cause losses. Banks face market risk through their trading activities, their investment portfolios, and their asset-liability mismatches. Unlike credit risk, which arises from specific borrower relationships, market risk arises from general market movements that affect many positions simultaneously.

Market risk includes several subcategories. Interest rate risk arises from changes in interest rates, which affect the value of fixed-income securities and the cost of funding. Foreign exchange risk arises from changes in exchange rates, which affect the value of foreign currency positions. Equity risk arises from changes in stock prices, which affect equity holdings. Commodity risk arises from changes in commodity prices, which affect commodity-related positions.

Banks measure market risk primarily using value-at-risk (VaR) models. VaR estimates the maximum loss that could occur over a specified time period with a specified confidence level. For example, a one-day VaR of $10 million at 95% confidence means that there is a 5% chance that losses will exceed $10 million in a single day.

The mathematical definition of VaR can be expressed as:

VaRα=inf⁡{x:P(L≤x)≥α}VaR_\alpha = \inf\{x: P(L \leq x) \geq \alpha\}

This equation states that VaR at confidence level α\alpha equals the infimum (greatest lower bound) of all values xx such that the probability of loss (LL) being less than or equal to xx is at least α\alpha. This captures the idea that VaR is the threshold loss that will be exceeded only with probability 1−α1-\alpha.

Banks manage market risk through several mechanisms. Position limits restrict the size of positions that can be taken. VaR limits restrict the total market risk that can be taken. Hedging uses offsetting positions to reduce risk. Stress testing evaluates how portfolios would perform under extreme market conditions. These mechanisms help banks control market risk while still allowing them to take positions that generate returns.

Let's visualize VaR calculations and market risk distributions:

Python exercise

#| label: banking-risk-1
#| fig-cap: "Value-at-Risk (VaR) Calculations and Market Risk Distributions"
#| fig-width: 16
#| fig-height: 10
#| echo: false
#| warning: false

# Sandbox metadata (auto-generated from lesson.ts)
# libraries: numpy, matplotlib

import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
from IPython.display import display

# Set style
plt.style.use('default')
plt.rcParams['figure.facecolor'] = 'white'
plt.rcParams['axes.grid'] = True
plt.rcParams['grid.alpha'] = 0.3
fig, axes = plt.subplots(2, 2, figsize=(16, 10))
fig.suptitle('Value-at-Risk (VaR) Calculations and Market Risk Distributions', 
             fontsize=16, fontweight='bold', y=0.995)

# 1. Portfolio Return Distribution and VaR
ax1 = axes[0, 0]
# Simulate portfolio returns (daily)
np.random.seed(42)
returns = np.random.normal(0.0005, 0.02, 1000)  # Mean return 0.05%, volatility 2%
portfolio_value = 1000000  # $1M portfolio

# Calculate VaR at 95% confidence
confidence_level = 0.95
var_95 = np.percentile(returns, (1 - confidence_level) * 100) * portfolio_value
var_99 = np.percentile(returns, (1 - 0.99) * 100) * portfolio_value

ax1.hist(returns * portfolio_value, bins=50, color='steelblue', alpha=0.7, 
         edgecolor='black', density=True)
ax1.axvline(var_95, color='red', linestyle='--', linewidth=2, 
            label=f'VaR 95%: ${abs(var_95):,.0f}')
ax1.axvline(var_99, color='darkred', linestyle='--', linewidth=2,
            label=f'VaR 99%: ${abs(var_99):,.0f}')
ax1.axvline(0, color='green', linestyle='-', linewidth=1, alpha=0.5)
ax1.set_xlabel('Portfolio P&L ($)', fontsize=11, fontweight='bold')
ax1.set_ylabel('Density', fontsize=11, fontweight='bold')
ax1.set_title('Portfolio Return Distribution and VaR', fontsize=12, fontweight='bold')
ax1.legend()
ax1.grid(True, alpha=0.3)

# 2. VaR Over Time (Rolling Window)
ax2 = axes[0, 1]
# Simulate 250 days of returns
days = 250
daily_returns = np.random.normal(0.0005, 0.02, days)
window = 60  # 60-day rolling window

rolling_var = []
for i in range(window, days):
    window_returns = daily_returns[i-window:i]
    var = np.percentile(window_returns, 5) * portfolio_value
    rolling_var.append(abs(var))

ax2.plot(range(window, days), rolling_var, color='crimson', linewidth=2, label='95% VaR')
ax2.fill_between(range(window, days), rolling_var, alpha=0.3, color='crimson')
ax2.axhline(np.mean(rolling_var), color='blue', linestyle='--', linewidth=2,
            label=f'Mean VaR: ${np.mean(rolling_var):,.0f}')
ax2.set_xlabel('Trading Day', fontsize=11, fontweight='bold')
ax2.set_ylabel('VaR ($)', fontsize=11, fontweight='bold')
ax2.set_title('Rolling 60-Day VaR Over Time', fontsize=12, fontweight='bold')
ax2.legend()
ax2.grid(True, alpha=0.3)

# 3. VaR by Confidence Level
ax3 = axes[1, 0]
confidence_levels = np.arange(0.90, 0.999, 0.005)
var_values = [np.percentile(returns, (1 - cl) * 100) * portfolio_value 
              for cl in confidence_levels]

ax3.plot(confidence_levels * 100, [abs(v) for v in var_values], 
         color='darkgreen', linewidth=2, marker='o', markersize=4)
ax3.fill_between(confidence_levels * 100, [abs(v) for v in var_values], 
                  alpha=0.3, color='darkgreen')
ax3.axvline(95, color='red', linestyle='--', linewidth=1, alpha=0.7, label='95% Confidence')
ax3.axvline(99, color='darkred', linestyle='--', linewidth=1, alpha=0.7, label='99% Confidence')
ax3.set_xlabel('Confidence Level (%)', fontsize=11, fontweight='bold')
ax3.set_ylabel('VaR ($)', fontsize=11, fontweight='bold')
ax3.set_title('VaR Sensitivity to Confidence Level', fontsize=12, fontweight='bold')
ax3.legend()
ax3.grid(True, alpha=0.3)

# 4. Market Risk Factors: Interest Rate, FX, Equity
ax4 = axes[1, 1]
# Simulate different market risk factors
days = 100
interest_rate_changes = np.random.normal(0, 0.001, days)  # Daily rate changes
fx_changes = np.random.normal(0, 0.015, days)  # FX volatility
equity_changes = np.random.normal(0.001, 0.025, days)  # Equity returns

x = range(days)
ax4.plot(x, np.cumsum(interest_rate_changes) * 100, label='Interest Rate Risk', 
         linewidth=2, color='blue')
ax4.plot(x, np.cumsum(fx_changes) * 100, label='FX Risk', 
         linewidth=2, color='orange')
ax4.plot(x, np.cumsum(equity_changes) * 100, label='Equity Risk', 
         linewidth=2, color='green')
ax4.axhline(0, color='black', linestyle='-', linewidth=0.5, alpha=0.3)
ax4.set_xlabel('Trading Day', fontsize=11, fontweight='bold')
ax4.set_ylabel('Cumulative Change (%)', fontsize=11, fontweight='bold')
ax4.set_title('Market Risk Factors Over Time', fontsize=12, fontweight='bold')
ax4.legend()
ax4.grid(True, alpha=0.3)

plt.tight_layout()
display(fig)
plt.close(fig)

Operational Risk: The Risk of Operational Failures

Operational risk is the risk of losses resulting from inadequate or failed internal processes, people, systems, or external events. This broad category includes risks such as fraud, system failures, human errors, legal risks, and business disruption. Operational risk is often more difficult to measure than credit or market risk because operational losses are less frequent, less predictable, and more diverse in their causes.

Operational risk includes several categories. Internal fraud involves employees or insiders stealing from the bank or committing other fraudulent acts. External fraud involves outsiders committing fraud against the bank, such as check fraud or cyberattacks. Employment practices and workplace safety risks include losses from discrimination claims, workplace accidents, or other employment-related issues. Clients, products, and business practices risks include losses from inappropriate sales practices, product defects, or model errors.

Banks measure operational risk using various approaches. Loss data collection tracks historical operational losses to understand patterns and magnitudes. Risk assessments evaluate the likelihood and impact of various operational risk scenarios. Key risk indicators monitor factors that might signal increased operational risk. These approaches help banks understand and quantify operational risk, though measurement remains challenging.

Banks manage operational risk through several mechanisms. Internal controls prevent and detect operational problems. Insurance transfers some operational risks to insurers. Business continuity planning ensures that operations can continue or resume quickly after disruptions. Technology investments improve system reliability and security. Training and culture promote operational excellence. These mechanisms help banks reduce operational risk, though they cannot eliminate it entirely.

Liquidity Risk and Funding Risk

Liquidity risk is the risk that a bank will be unable to meet its obligations as they come due without incurring unacceptable losses. This risk arises from the fundamental nature of banking - banks borrow short-term (through deposits) and lend long-term (through loans), creating a maturity mismatch. If depositors withdraw funds faster than expected, or if the bank cannot roll over its funding, the bank may face liquidity problems.

Funding risk is closely related to liquidity risk and refers specifically to the risk that a bank will be unable to obtain funding at reasonable costs. Banks need funding to support their assets, and if funding becomes unavailable or too expensive, the bank may be forced to sell assets at distressed prices or reduce lending, both of which can cause losses.

Liquidity risk has several dimensions. Funding liquidity risk is the risk that the bank cannot obtain funding when needed. Market liquidity risk is the risk that the bank cannot sell assets quickly without significant price discounts. Both types of liquidity risk can threaten a bank's survival, as banks need liquidity to operate and to meet obligations.

Banks manage liquidity risk through several mechanisms. Liquidity buffers hold highly liquid assets that can be sold quickly if needed. Diversified funding sources reduce dependence on any single source. Contingency funding plans prepare for liquidity stress scenarios. Asset-liability management matches the maturities and characteristics of assets and liabilities. Regulatory requirements mandate minimum liquidity levels. These mechanisms help banks maintain adequate liquidity, though liquidity risk can never be completely eliminated.

Credit Risk Management

Credit risk management is central to banking, as credit risk is typically the largest risk that banks face. Effective credit risk management requires sophisticated models, careful underwriting, ongoing monitoring, and appropriate risk controls. Understanding how banks manage credit risk helps explain how banking systems function and how credit is allocated in the economy.

Probability of Default (PD) Models

Probability of default models estimate the likelihood that borrowers will default on their obligations. These models use various inputs - borrower characteristics, financial ratios, credit scores, economic conditions - to predict default probability. PD models are essential for credit underwriting, pricing, and risk management.

PD models can be based on statistical techniques such as logistic regression, which estimates the probability of default as a function of borrower characteristics. They can also be based on credit rating systems, where borrowers are assigned ratings that correspond to historical default rates. More sophisticated models use machine learning techniques to identify complex patterns in data that predict default.

PD models must be validated regularly to ensure they remain accurate. Model validation involves comparing predicted default rates to actual default rates, testing model assumptions, and ensuring that models perform well across different economic conditions and borrower segments. Poorly validated or outdated models can lead to significant credit losses.

The accuracy of PD models can be measured using various metrics. The area under the receiver operating characteristic curve (AUC-ROC) measures how well the model distinguishes between defaulters and non-defaulters. The Brier score measures the accuracy of probability predictions. These metrics help banks assess model quality and identify models that need improvement.

Loss Given Default (LGD) Estimation

Loss given default measures the percentage of exposure that will be lost if default occurs. LGD depends on factors such as collateral value, recovery processes, and the seniority of the claim. Estimating LGD accurately is important because it directly affects expected loss calculations and credit pricing.

LGD estimation is challenging because it requires predicting recovery rates, which depend on factors that are difficult to predict - collateral values, legal processes, economic conditions at the time of default. Banks typically estimate LGD using historical recovery data, adjusted for current conditions and specific loan characteristics.

LGD varies significantly across different types of credit. Secured loans, where the bank has collateral, typically have lower LGD than unsecured loans. Senior debt typically has lower LGD than subordinated debt. Different types of collateral have different LGD characteristics - real estate collateral might have different recovery rates than equipment collateral.

Banks manage LGD through several mechanisms. Collateral requirements reduce LGD by providing assets that can be seized and sold if default occurs. Guarantees and credit insurance transfer some LGD risk to third parties. Recovery processes aim to maximize recovery and minimize losses. These mechanisms help banks reduce LGD, though they cannot eliminate credit losses entirely.

Exposure at Default (EAD) Calculation

Exposure at default measures the amount that will be outstanding at the time of default. For term loans, EAD is typically the outstanding principal balance. For revolving credit facilities such as credit cards or lines of credit, EAD is more complex because the borrower can draw additional funds before default, potentially increasing exposure.

EAD calculation for revolving facilities requires modeling drawdown behavior - predicting how much borrowers will draw before defaulting. This modeling is challenging because drawdown behavior can change during stress periods, and borrowers might draw more when they are in financial distress, increasing EAD.

Banks manage EAD through several mechanisms. Credit limits restrict the maximum exposure that can be taken. Monitoring systems track exposure levels and identify increases that might signal problems. Early warning systems identify borrowers who might be heading toward default, allowing banks to reduce exposure before default occurs.

Credit Risk Portfolio Models

Credit risk portfolio models analyze credit risk at the portfolio level, recognizing that credit risks are not independent - defaults can be correlated due to common economic factors, industry conditions, or geographic concentrations. Portfolio models help banks understand portfolio-level risk, optimize portfolio composition, and allocate capital efficiently.

Portfolio credit risk models typically use Monte Carlo simulation or analytical approximations to estimate portfolio loss distributions. These models incorporate default correlations, which measure how likely it is that multiple borrowers will default simultaneously. High correlations increase portfolio risk because defaults are more likely to occur together, creating larger losses.

The credit VaR (conditional value-at-risk) measures expected losses conditional on losses exceeding VaR:

CVaR=E[L∣L>VaR]CVaR = E[L|L > VaR]

This equation states that credit VaR (CVaRCVaR) equals the expected loss (E[L∣L>VaR]E[L|L > VaR]) conditional on losses exceeding VaR. This captures tail risk - the risk of extreme losses that occur when multiple defaults happen simultaneously.

Let's visualize credit risk portfolio analysis:

Python exercise

#| label: banking-risk-2
#| fig-cap: "Credit Risk Portfolio Analysis: Correlation and Diversification"
#| fig-width: 16
#| fig-height: 10
#| echo: false
#| warning: false

# Sandbox metadata (auto-generated from lesson.ts)
# libraries: numpy, matplotlib

import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
from IPython.display import display

# Set style
plt.style.use('default')
plt.rcParams['figure.facecolor'] = 'white'
plt.rcParams['axes.grid'] = True
plt.rcParams['grid.alpha'] = 0.3
fig, axes = plt.subplots(2, 2, figsize=(16, 10))
fig.suptitle('Credit Risk Portfolio Analysis: Correlation and Diversification Effects', 
             fontsize=16, fontweight='bold', y=0.995)

# 1. Portfolio Loss Distribution (Monte Carlo Simulation)
ax1 = axes[0, 0]
np.random.seed(42)
n_loans = 100
n_simulations = 10000
portfolio_exposure = 10000000  # $10M portfolio

# Simulate defaults with correlation
default_correlation = 0.2
pd_base = 0.05  # 5% base PD

# Generate correlated defaults using Gaussian copula
z = np.random.normal(0, 1, (n_simulations, n_loans))
common_factor = np.random.normal(0, 1, n_simulations).reshape(-1, 1)
correlated_z = np.sqrt(default_correlation) * common_factor + np.sqrt(1 - default_correlation) * z
defaults = (correlated_z < stats.norm.ppf(pd_base)).sum(axis=1)

# Calculate portfolio losses (assuming 50% LGD)
lgd = 0.5
loss_per_loan = portfolio_exposure / n_loans
portfolio_losses = defaults * loss_per_loan * lgd

ax1.hist(portfolio_losses, bins=50, color='steelblue', alpha=0.7, edgecolor='black', density=True)
mean_loss = np.mean(portfolio_losses)
var_95 = np.percentile(portfolio_losses, 95)
ax1.axvline(mean_loss, color='green', linestyle='--', linewidth=2, 
            label=f'Expected Loss: ${mean_loss:,.0f}')
ax1.axvline(var_95, color='red', linestyle='--', linewidth=2,
            label=f'95% VaR: ${var_95:,.0f}')
ax1.set_xlabel('Portfolio Loss ($)', fontsize=11, fontweight='bold')
ax1.set_ylabel('Density', fontsize=11, fontweight='bold')
ax1.set_title('Portfolio Loss Distribution (Monte Carlo)', fontsize=12, fontweight='bold')
ax1.legend()
ax1.grid(True, alpha=0.3)

# 2. Effect of Default Correlation on Portfolio Risk
ax2 = axes[0, 1]
correlations = np.arange(0, 0.6, 0.05)
var_95_values = []

for corr in correlations:
    z = np.random.normal(0, 1, (5000, n_loans))
    common_factor = np.random.normal(0, 1, 5000).reshape(-1, 1)
    correlated_z = np.sqrt(corr) * common_factor + np.sqrt(1 - corr) * z
    defaults = (correlated_z < stats.norm.ppf(pd_base)).sum(axis=1)
    losses = defaults * loss_per_loan * lgd
    var_95_values.append(np.percentile(losses, 95))

ax2.plot(correlations, var_95_values, color='crimson', linewidth=2, marker='o', markersize=6)
ax2.fill_between(correlations, var_95_values, alpha=0.3, color='crimson')
ax2.set_xlabel('Default Correlation', fontsize=11, fontweight='bold')
ax2.set_ylabel('95% VaR ($)', fontsize=11, fontweight='bold')
ax2.set_title('Portfolio Risk vs Default Correlation', fontsize=12, fontweight='bold')
ax2.grid(True, alpha=0.3)
ax2.text(0.3, max(var_95_values) * 0.7, 'Higher correlation\nincreases tail risk', 
         fontsize=10, bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))

# 3. Diversification Benefit: Portfolio Size
ax3 = axes[1, 0]
portfolio_sizes = [10, 25, 50, 100, 200, 500, 1000]
portfolio_var = []

for size in portfolio_sizes:
    z = np.random.normal(0, 1, (5000, size))
    common_factor = np.random.normal(0, 1, 5000).reshape(-1, 1)
    correlated_z = np.sqrt(0.2) * common_factor + np.sqrt(0.8) * z
    defaults = (correlated_z < stats.norm.ppf(pd_base)).sum(axis=1)
    exposure_per_loan = portfolio_exposure / size
    losses = defaults * exposure_per_loan * lgd
    portfolio_var.append(np.percentile(losses, 95))

ax3.plot(portfolio_sizes, portfolio_var, color='darkgreen', linewidth=2, 
         marker='o', markersize=6)
ax3.fill_between(portfolio_sizes, portfolio_var, alpha=0.3, color='darkgreen')
ax3.set_xlabel('Number of Loans in Portfolio', fontsize=11, fontweight='bold')
ax3.set_ylabel('95% VaR ($)', fontsize=11, fontweight='bold')
ax3.set_title('Diversification Benefit: Risk vs Portfolio Size', fontsize=12, fontweight='bold')
ax3.set_xscale('log')
ax3.grid(True, alpha=0.3)
ax3.text(50, max(portfolio_var) * 0.8, 'Diversification\nreduces risk', 
         fontsize=10, bbox=dict(boxstyle='round', facecolor='lightblue', alpha=0.5))

# 4. Credit VaR (Conditional VaR) vs Regular VaR
ax4 = axes[1, 1]
# Calculate CVaR (Expected Shortfall)
var_95_threshold = np.percentile(portfolio_losses, 95)
cvar_95 = portfolio_losses[portfolio_losses >= var_95_threshold].mean()

# Create comparison
categories = ['Expected\nLoss', '95% VaR', '95% CVaR\n(Expected Shortfall)']
values = [mean_loss, var_95, cvar_95]
colors = ['green', 'orange', 'red']

bars = ax4.bar(categories, values, color=colors, alpha=0.7, edgecolor='black', linewidth=2)
ax4.set_ylabel('Loss ($)', fontsize=11, fontweight='bold')
ax4.set_title('Credit Risk Measures: EL, VaR, and CVaR', fontsize=12, fontweight='bold')
ax4.grid(True, alpha=0.3, axis='y')

# Add value labels on bars
for bar, val in zip(bars, values):
    height = bar.get_height()
    ax4.text(bar.get_x() + bar.get_width()/2., height,
             f'${val:,.0f}',
             ha='center', va='bottom', fontsize=10, fontweight='bold')

plt.tight_layout()
display(fig)
plt.close(fig)

Market Risk Management

Market risk management is essential for banks that engage in trading activities or hold investment portfolios. Effective market risk management requires accurate risk measurement, appropriate risk limits, effective hedging, and robust stress testing. Understanding market risk management helps explain how banks can take market positions while controlling risk.

Value-at-Risk (VaR) Models

VaR models are the primary tool for measuring market risk. These models estimate the maximum loss that could occur over a specified time period with a specified confidence level. VaR provides a single number that summarizes market risk, making it useful for risk limits, capital allocation, and risk reporting.

VaR models can be implemented using various approaches. Historical simulation uses historical price movements to estimate potential future losses. Parametric approaches assume that returns follow specific distributions (such as normal distributions) and estimate VaR using distribution parameters. Monte Carlo simulation generates many possible future scenarios and estimates VaR from the distribution of simulated outcomes.

Each approach has advantages and limitations. Historical simulation is simple and makes no distributional assumptions, but it assumes that the future will resemble the past. Parametric approaches are computationally efficient, but they may not capture tail risks if returns are not normally distributed. Monte Carlo simulation is flexible and can incorporate complex dependencies, but it is computationally intensive.

VaR models must be validated regularly to ensure they remain accurate. Backtesting compares predicted VaR to actual losses to assess model accuracy. If actual losses exceed VaR more frequently than expected, the model may be underestimating risk. If actual losses rarely exceed VaR, the model may be overestimating risk, though this is less problematic.

Let's visualize VaR calculation methods and their applications:

Python exercise

#| label: banking-risk-3
#| fig-cap: "VaR Calculation Methods: Historical, Parametric, and Monte Carlo"
#| fig-width: 16
#| fig-height: 10
#| echo: false
#| warning: false

# Sandbox metadata (auto-generated from lesson.ts)
# libraries: numpy, matplotlib

import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
from IPython.display import display

# Set style
plt.style.use('default')
plt.rcParams['figure.facecolor'] = 'white'
plt.rcParams['axes.grid'] = True
plt.rcParams['grid.alpha'] = 0.3
fig, axes = plt.subplots(2, 2, figsize=(16, 10))
fig.suptitle('VaR Calculation Methods: Historical, Parametric, and Monte Carlo', 
             fontsize=16, fontweight='bold', y=0.995)

np.random.seed(42)
portfolio_value = 1000000
confidence_level = 0.95
n_days = 252  # One year of trading days

# Generate historical returns
historical_returns = np.random.normal(0.0005, 0.02, n_days)

# 1. Historical Simulation VaR
ax1 = axes[0, 0]
# Use last 60 days for historical simulation
window = 60
historical_window = historical_returns[-window:]
historical_var = np.percentile(historical_window, (1 - confidence_level) * 100) * portfolio_value

ax1.hist(historical_window * portfolio_value, bins=20, color='steelblue', alpha=0.7, 
         edgecolor='black', density=True)
ax1.axvline(historical_var, color='red', linestyle='--', linewidth=2,
            label=f'Historical VaR 95%: ${abs(historical_var):,.0f}')
ax1.axvline(0, color='green', linestyle='-', linewidth=1, alpha=0.5)
ax1.set_xlabel('Portfolio P&L ($)', fontsize=11, fontweight='bold')
ax1.set_ylabel('Density', fontsize=11, fontweight='bold')
ax1.set_title('Historical Simulation VaR', fontsize=12, fontweight='bold')
ax1.legend()
ax1.grid(True, alpha=0.3)

# 2. Parametric VaR (Normal Distribution)
ax2 = axes[0, 1]
# Assume returns are normally distributed
mean_return = np.mean(historical_returns)
std_return = np.std(historical_returns)
z_score = stats.norm.ppf(1 - confidence_level)
parametric_var = (mean_return - z_score * std_return) * portfolio_value

# Plot normal distribution
x = np.linspace(mean_return - 4*std_return, mean_return + 4*std_return, 100)
normal_pdf = stats.norm.pdf(x, mean_return, std_return)
ax2.plot(x * portfolio_value, normal_pdf, color='darkgreen', linewidth=2, label='Normal Distribution')
ax2.hist(historical_returns * portfolio_value, bins=30, color='steelblue', alpha=0.5, 
         edgecolor='black', density=True, label='Actual Returns')
ax2.axvline(parametric_var, color='red', linestyle='--', linewidth=2,
            label=f'Parametric VaR 95%: ${abs(parametric_var):,.0f}')
ax2.axvline(0, color='green', linestyle='-', linewidth=1, alpha=0.5)
ax2.set_xlabel('Portfolio P&L ($)', fontsize=11, fontweight='bold')
ax2.set_ylabel('Density', fontsize=11, fontweight='bold')
ax2.set_title('Parametric VaR (Normal Distribution)', fontsize=12, fontweight='bold')
ax2.legend()
ax2.grid(True, alpha=0.3)

# 3. Monte Carlo Simulation VaR
ax3 = axes[1, 0]
# Generate many scenarios
n_simulations = 10000
mc_returns = np.random.normal(mean_return, std_return, n_simulations)
mc_var = np.percentile(mc_returns, (1 - confidence_level) * 100) * portfolio_value

ax3.hist(mc_returns * portfolio_value, bins=50, color='purple', alpha=0.7, 
         edgecolor='black', density=True)
ax3.axvline(mc_var, color='red', linestyle='--', linewidth=2,
            label=f'Monte Carlo VaR 95%: ${abs(mc_var):,.0f}')
ax3.axvline(0, color='green', linestyle='-', linewidth=1, alpha=0.5)
ax3.set_xlabel('Portfolio P&L ($)', fontsize=11, fontweight='bold')
ax3.set_ylabel('Density', fontsize=11, fontweight='bold')
ax3.set_title('Monte Carlo Simulation VaR', fontsize=12, fontweight='bold')
ax3.legend()
ax3.grid(True, alpha=0.3)

# 4. Comparison of VaR Methods
ax4 = axes[1, 1]
methods = ['Historical\nSimulation', 'Parametric\n(Normal)', 'Monte Carlo\nSimulation']
var_values = [abs(historical_var), abs(parametric_var), abs(mc_var)]
colors = ['steelblue', 'darkgreen', 'purple']

bars = ax4.bar(methods, var_values, color=colors, alpha=0.7, edgecolor='black', linewidth=2)
ax4.set_ylabel('VaR 95% ($)', fontsize=11, fontweight='bold')
ax4.set_title('Comparison of VaR Calculation Methods', fontsize=12, fontweight='bold')
ax4.grid(True, alpha=0.3, axis='y')

# Add value labels
for bar, val in zip(bars, var_values):
    height = bar.get_height()
    ax4.text(bar.get_x() + bar.get_width()/2., height,
             f'${val:,.0f}',
             ha='center', va='bottom', fontsize=10, fontweight='bold')

# Add text annotation
ax4.text(0.5, 0.95, f'Mean: ${np.mean(var_values):,.0f}\nStd: ${np.std(var_values):,.0f}',
         transform=ax4.transAxes, fontsize=9,
         bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5),
         verticalalignment='top')

plt.tight_layout()
display(fig)
plt.close(fig)

Stress Testing and Scenario Analysis

Stress testing evaluates how portfolios would perform under extreme but plausible market conditions. Unlike VaR, which focuses on normal market conditions, stress testing examines tail events - rare but severe market movements that could cause significant losses. Stress testing helps banks understand their vulnerability to extreme events and prepare for them.

Stress tests can be based on historical scenarios - examining how portfolios would have performed during past crises such as the 2008 financial crisis or the 2020 COVID-19 market crash. They can also be based on hypothetical scenarios - imagining extreme but plausible future events such as a sudden interest rate spike or a major currency devaluation.

Stress testing helps banks in several ways. It identifies vulnerabilities that might not be apparent from normal risk measures. It helps banks prepare contingency plans for extreme events. It satisfies regulatory requirements, as regulators require banks to conduct stress tests regularly. It helps banks communicate risk to stakeholders.

The mathematical framework for stress testing can be expressed as:

Lstress=f(Xstress,β)L_{stress} = f(X_{stress}, \beta)

This equation states that stress loss (RWA=∑iwi×EADiRWA = \sum_i w_i \times EAD_i) is a function (CAR=CapitalRWA≥8%CAR = \frac{Capital}{RWA} \geq 8\%) of stressed market factors (CARCAR) and portfolio sensitivities (). Stress tests specify extreme values for market factors and calculate resulting losses.

Let's visualize stress test scenarios and their impact:

Python exercise

#| label: banking-risk-4
#| fig-cap: "Stress Testing: Scenario Analysis and Impact Assessment"
#| fig-width: 16
#| fig-height: 10
#| echo: false
#| warning: false

# Sandbox metadata (auto-generated from lesson.ts)
# libraries: numpy, matplotlib

import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display

# Set style
plt.style.use('default')
plt.rcParams['figure.facecolor'] = 'white'
plt.rcParams['axes.grid'] = True
plt.rcParams['grid.alpha'] = 0.3
fig, axes = plt.subplots(2, 2, figsize=(16, 10))
fig.suptitle('Stress Testing: Scenario Analysis and Impact Assessment', 
             fontsize=16, fontweight='bold', y=0.995)

portfolio_value = 1000000
base_return = 0.0005
base_volatility = 0.02

# 1. Historical Stress Scenarios
ax1 = axes[0, 0]
scenarios = ['2008 Financial\nCrisis', '2020 COVID-19\nMarket Crash', '2015 China\nDevaluation', 
             '1997 Asian\nFinancial Crisis', 'Normal\nConditions']
# Simulated stress losses (negative returns)
stress_losses = [-0.15, -0.12, -0.08, -0.10, -0.02]  # As percentages
stress_pnl = [loss * portfolio_value for loss in stress_losses]

colors = ['darkred', 'crimson', 'orange', 'salmon', 'lightblue']
bars = ax1.barh(scenarios, stress_pnl, color=colors, alpha=0.7, edgecolor='black', linewidth=2)
ax1.axvline(0, color='black', linestyle='-', linewidth=1)
ax1.set_xlabel('Portfolio P&L ($)', fontsize=11, fontweight='bold')
ax1.set_title('Historical Stress Scenarios: Portfolio Impact', fontsize=12, fontweight='bold')
ax1.grid(True, alpha=0.3, axis='x')

# Add value labels
for bar, val in zip(bars, stress_pnl):
    width = bar.get_width()
    ax1.text(width, bar.get_y() + bar.get_height()/2.,
             f'${val:,.0f}',
             ha='left' if width < 0 else 'right', va='center', fontsize=9, fontweight='bold')

# 2. Hypothetical Stress Scenarios
ax2 = axes[0, 1]
# Interest rate shock scenarios
rate_shocks = ['+200 bps\nRate Spike', '+100 bps\nModerate', 'Base Case', 
               '-100 bps\nModerate', '-200 bps\nRate Drop']
rate_changes = [0.02, 0.01, 0, -0.01, -0.02]
# Simulate portfolio sensitivity (duration effect)
duration = 5  # 5-year duration
portfolio_impact = [-duration * change * portfolio_value for change in rate_changes]

colors2 = ['darkred', 'orange', 'green', 'lightblue', 'steelblue']
bars2 = ax2.bar(rate_shocks, portfolio_impact, color=colors2, alpha=0.7, 
                edgecolor='black', linewidth=2)
ax2.axhline(0, color='black', linestyle='-', linewidth=1)
ax2.set_ylabel('Portfolio Impact ($)', fontsize=11, fontweight='bold')
ax2.set_title('Interest Rate Stress Scenarios', fontsize=12, fontweight='bold')
ax2.grid(True, alpha=0.3, axis='y')
ax2.tick_params(axis='x', rotation=45)

# Add value labels
for bar, val in zip(bars2, portfolio_impact):
    height = bar.get_height()
    ax2.text(bar.get_x() + bar.get_width()/2., height,
             f'${val:,.0f}',
             ha='center', va='bottom' if height > 0 else 'top', fontsize=9, fontweight='bold')

# 3. Stress Test Over Time (Cumulative Impact)
ax3 = axes[1, 0]
# Simulate stress scenario unfolding over 20 days
days = 20
stress_days = np.arange(days)
# Stress scenario: gradual deterioration
stress_returns = -0.01 * np.exp(-stress_days / 5) + np.random.normal(0, 0.005, days)
cumulative_pnl = np.cumsum(stress_returns) * portfolio_value

ax3.plot(stress_days, cumulative_pnl, color='darkred', linewidth=2, marker='o', markersize=6)
ax3.fill_between(stress_days, cumulative_pnl, 0, alpha=0.3, color='darkred', where=(cumulative_pnl < 0))
ax3.axhline(0, color='black', linestyle='-', linewidth=1)
ax3.axhline(-portfolio_value * 0.1, color='red', linestyle='--', linewidth=2,
            label='10% Loss Threshold', alpha=0.7)
ax3.set_xlabel('Days into Stress Scenario', fontsize=11, fontweight='bold')
ax3.set_ylabel('Cumulative P&L ($)', fontsize=11, fontweight='bold')
ax3.set_title('Stress Scenario: Cumulative Impact Over Time', fontsize=12, fontweight='bold')
ax3.legend()
ax3.grid(True, alpha=0.3)

# 4. Stress Test Results: Capital Impact
ax4 = axes[1, 1]
# Simulate capital ratios under different scenarios
scenarios_capital = ['Baseline', 'Mild Stress', 'Moderate Stress', 'Severe Stress', 'Extreme Stress']
capital_ratios = [12.5, 11.0, 9.5, 7.8, 6.2]  # Capital adequacy ratios (%)
regulatory_minimum = 8.0

colors3 = ['green', 'lightgreen', 'yellow', 'orange', 'red']
bars3 = ax4.bar(scenarios_capital, capital_ratios, color=colors3, alpha=0.7, 
                edgecolor='black', linewidth=2)
ax4.axhline(regulatory_minimum, color='red', linestyle='--', linewidth=2,
            label=f'Regulatory Minimum: {regulatory_minimum}%')
ax4.set_ylabel('Capital Adequacy Ratio (%)', fontsize=11, fontweight='bold')
ax4.set_title('Capital Impact Under Stress Scenarios', fontsize=12, fontweight='bold')
ax4.legend()
ax4.grid(True, alpha=0.3, axis='y')
ax4.tick_params(axis='x', rotation=45)

# Add value labels
for bar, val in zip(bars3, capital_ratios):
    height = bar.get_height()
    color = 'red' if val < regulatory_minimum else 'black'
    ax4.text(bar.get_x() + bar.get_width()/2., height,
             f'{val:.1f}%',
             ha='center', va='bottom', fontsize=9, fontweight='bold', color=color)

plt.tight_layout()
display(fig)
plt.close(fig)

Risk Limits and Monitoring

Risk limits restrict the amount of risk that can be taken, helping banks control their risk exposure. Limits can be set at various levels - for individual traders, trading desks, business units, or the entire bank. Limits can be based on various risk measures - VaR, position size, notional exposure, or other metrics.

Effective risk limits require several elements. Limits must be appropriate for the risk being taken - too tight limits might prevent profitable opportunities, while too loose limits might allow excessive risk. Limits must be monitored in real-time to ensure they are not exceeded. Limits must be enforced - violations must trigger appropriate responses, such as position reductions or trading restrictions.

Risk monitoring systems track risk measures continuously and alert risk managers when limits are approached or exceeded. These systems must be fast enough to provide timely warnings, accurate enough to reflect actual risk, and comprehensive enough to capture all relevant risks. Modern risk monitoring systems use sophisticated technology to provide real-time risk visibility.

Operational Risk

Operational risk is often called the "risk of doing business" because it arises from the normal operations of the bank. While operational losses are typically smaller than credit or market losses, they can still be significant, and operational risk failures can damage a bank's reputation and customer relationships. Understanding operational risk helps explain why banks invest heavily in systems, controls, and processes.

Operational Risk Categories

Operational risk includes several broad categories. Internal fraud involves employees or insiders committing fraud against the bank. External fraud involves outsiders committing fraud against the bank. Employment practices and workplace safety risks include losses from employment-related claims or workplace accidents. Clients, products, and business practices risks include losses from inappropriate practices, product defects, or model errors.

Damage to physical assets includes losses from fires, natural disasters, or other events that damage bank property. Business disruption and system failures include losses from technology failures, power outages, or other disruptions that prevent normal operations. Execution, delivery, and process management risks include losses from errors in transaction processing, settlement failures, or other operational mistakes.

Each category has different characteristics and requires different management approaches. Some categories, such as fraud, require strong internal controls and monitoring. Other categories, such as system failures, require robust technology and redundancy. Understanding these differences helps banks allocate resources effectively to manage operational risk.

Loss Data Collection

Loss data collection tracks historical operational losses to understand patterns, magnitudes, and frequencies. This data is essential for operational risk modeling, as it provides the empirical basis for estimating operational risk. However, loss data collection faces challenges - operational losses are infrequent, diverse, and sometimes difficult to categorize.

Banks collect loss data through various mechanisms. Internal loss databases track losses that occur within the bank. External loss databases provide information about losses at other banks, which helps banks understand risks that might not yet have occurred at their bank. Loss data must be comprehensive, accurate, and timely to be useful for risk management.

Loss data analysis helps banks understand operational risk in several ways. It identifies the most significant loss categories and helps prioritize risk management efforts. It provides data for operational risk models that estimate potential future losses. It helps banks benchmark their operational risk against peers. It supports regulatory capital calculations for operational risk.

Risk Assessment Methodologies

Operational risk assessment evaluates the likelihood and impact of various operational risk scenarios. Unlike credit and market risk, which can be measured using quantitative models, operational risk assessment often relies more heavily on qualitative judgment, though quantitative elements are increasingly important.

Risk assessment methodologies include risk and control self-assessments, where business units evaluate their own operational risks and controls. They include key risk indicators, which monitor factors that might signal increased operational risk. They include scenario analysis, which evaluates how various operational risk events might affect the bank.

These methodologies help banks understand operational risk even when quantitative measurement is difficult. They help identify areas where operational risk might be increasing. They help prioritize risk management efforts. They support regulatory capital calculations and risk reporting.

Regulatory Capital Framework

Regulatory capital requirements ensure that banks hold sufficient capital to absorb losses and remain solvent. The Basel framework, developed by the Basel Committee on Banking Supervision, provides international standards for regulatory capital. Understanding this framework helps explain how banks are regulated and how capital requirements affect banking behavior.

Basel III Capital Requirements

Basel III, the current version of the Basel framework, establishes minimum capital requirements for banks. Banks must hold capital equal to at least 8% of risk-weighted assets, with at least 4.5% in common equity tier 1 capital and at least 6% in tier 1 capital. These requirements ensure that banks have sufficient high-quality capital to absorb losses.

Risk-weighted assets (RWA) adjust asset values for risk, so that riskier assets require more capital. The calculation of RWA can be expressed as:

RWA=∑iwi×EADiRWA = \sum_i w_i \times EAD_i

This equation states that RWA equals the sum across all assets of risk weights (CAR=CapitalRWA≥8%CAR = \frac{Capital}{RWA} \geq 8\%) times exposure at default (CARCAR). Risk weights vary by asset type - government bonds might have low risk weights, while corporate loans might have higher risk weights.

The capital adequacy ratio measures whether banks meet capital requirements:

CAR=CapitalRWA≥8%CAR = \frac{Capital}{RWA} \geq 8\%

This equation states that the capital adequacy ratio (CARCAR) equals capital divided by RWA, and must be at least 8%. Banks that fall below this ratio face regulatory restrictions and may be required to raise capital or reduce risk.

Let's visualize capital adequacy and regulatory requirements:

Python exercise

#| label: banking-risk-5
#| fig-cap: "Capital Adequacy and Regulatory Requirements: Basel III Framework"
#| fig-width: 16
#| fig-height: 10
#| echo: false
#| warning: false

# Sandbox metadata (auto-generated from lesson.ts)
# libraries: numpy, matplotlib

import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display

# Set style
plt.style.use('default')
plt.rcParams['figure.facecolor'] = 'white'
plt.rcParams['axes.grid'] = True
plt.rcParams['grid.alpha'] = 0.3
fig, axes = plt.subplots(2, 2, figsize=(16, 10))
fig.suptitle('Capital Adequacy and Regulatory Requirements: Basel III Framework', 
             fontsize=16, fontweight='bold', y=0.995)

# 1. Capital Structure: Tier 1, Tier 2, Total Capital
ax1 = axes[0, 0]
total_assets = 1000000000  # $1B bank
rwa = 750000000  # Risk-weighted assets

# Basel III requirements
tier1_common = 0.045 * rwa  # 4.5% minimum
tier1_additional = 0.015 * rwa  # Additional tier 1 (1.5%)
tier2 = 0.02 * rwa  # Tier 2 capital (2%)
total_capital_required = 0.08 * rwa  # 8% total

# Actual bank capital (slightly above minimum)
actual_tier1_common = 0.06 * rwa
actual_tier1_additional = 0.02 * rwa
actual_tier2 = 0.025 * rwa

categories = ['Tier 1\nCommon Equity', 'Additional\nTier 1', 'Tier 2\nCapital']
required = [tier1_common, tier1_additional, tier2]
actual = [actual_tier1_common, actual_tier1_additional, actual_tier2]

x = np.arange(len(categories))
width = 0.35

bars1 = ax1.bar(x - width/2, [v/1e6 for v in required], width, label='Required', 
                color='lightcoral', alpha=0.7, edgecolor='black')
bars2 = ax1.bar(x + width/2, [v/1e6 for v in actual], width, label='Actual', 
                color='lightgreen', alpha=0.7, edgecolor='black')

ax1.set_ylabel('Capital ($ millions)', fontsize=11, fontweight='bold')
ax1.set_title('Capital Structure: Required vs Actual', fontsize=12, fontweight='bold')
ax1.set_xticks(x)
ax1.set_xticklabels(categories)
ax1.legend()
ax1.grid(True, alpha=0.3, axis='y')

# Add value labels
for bars in [bars1, bars2]:
    for bar in bars:
        height = bar.get_height()
        ax1.text(bar.get_x() + bar.get_width()/2., height,
                f'${height:.1f}M',
                ha='center', va='bottom', fontsize=8, fontweight='bold')

# 2. Capital Adequacy Ratio Over Time
ax2 = axes[0, 1]
# Simulate capital ratio over 5 years
years = np.arange(2020, 2025)
capital_ratios = [12.5, 11.8, 10.5, 9.2, 8.5]  # Declining due to stress
regulatory_minimum = 8.0
tier1_minimum = 6.0

ax2.plot(years, capital_ratios, color='darkblue', linewidth=2, marker='o', markersize=8, label='Total Capital Ratio')
ax2.fill_between(years, capital_ratios, regulatory_minimum, alpha=0.3, color='lightblue', where=(np.array(capital_ratios) >= regulatory_minimum))
ax2.fill_between(years, capital_ratios, regulatory_minimum, alpha=0.3, color='lightcoral', where=(np.array(capital_ratios) < regulatory_minimum))
ax2.axhline(regulatory_minimum, color='red', linestyle='--', linewidth=2, label=f'Minimum: {regulatory_minimum}%')
ax2.axhline(tier1_minimum, color='orange', linestyle='--', linewidth=2, label=f'Tier 1 Minimum: {tier1_minimum}%')
ax2.set_xlabel('Year', fontsize=11, fontweight='bold')
ax2.set_ylabel('Capital Adequacy Ratio (%)', fontsize=11, fontweight='bold')
ax2.set_title('Capital Adequacy Ratio Trend', fontsize=12, fontweight='bold')
ax2.legend()
ax2.grid(True, alpha=0.3)

# 3. Risk-Weighted Assets by Asset Type
ax3 = axes[1, 0]
asset_types = ['Government\nBonds', 'Corporate\nLoans', 'Mortgages', 'Equities', 'Other\nAssets']
exposures = [200, 300, 250, 100, 100]  # $ millions
risk_weights = [0.0, 1.0, 0.35, 1.0, 0.5]  # Risk weights (0-1)
rwa_by_type = [e * rw for e, rw in zip(exposures, risk_weights)]

colors = ['green', 'red', 'orange', 'darkred', 'gray']
bars3 = ax3.bar(asset_types, rwa_by_type, color=colors, alpha=0.7, edgecolor='black', linewidth=2)
ax3.set_ylabel('Risk-Weighted Assets ($ millions)', fontsize=11, fontweight='bold')
ax3.set_title('RWA Breakdown by Asset Type', fontsize=12, fontweight='bold')
ax3.grid(True, alpha=0.3, axis='y')

# Add value labels and risk weights
for bar, val, rw in zip(bars3, rwa_by_type, risk_weights):
    height = bar.get_height()
    ax3.text(bar.get_x() + bar.get_width()/2., height,
             f'${val:.0f}M\n(RW: {rw*100:.0f}%)',
             ha='center', va='bottom', fontsize=8, fontweight='bold')

# 4. Capital Buffer Requirements
ax4 = axes[1, 1]
buffer_types = ['Minimum\nCapital', 'Capital\nConservation\nBuffer', 'Countercyclical\nBuffer', 
                'Systemic\nRisk Buffer', 'Stress Capital\nBuffer']
buffer_amounts = [8.0, 2.5, 0.0, 1.0, 2.0]  # Percentages
cumulative = np.cumsum(buffer_amounts)

colors4 = ['red', 'orange', 'yellow', 'lightgreen', 'darkgreen']
bars4 = ax4.barh(buffer_types, buffer_amounts, color=colors4, alpha=0.7, edgecolor='black', linewidth=2)

# Add cumulative line
ax4_twin = ax4.twiny()
ax4_twin.plot(cumulative, range(len(buffer_types)), color='darkblue', linewidth=2, 
              marker='o', markersize=8, label='Cumulative Requirement')
ax4_twin.set_xlabel('Cumulative Capital Requirement (%)', fontsize=11, fontweight='bold')
ax4_twin.axvline(8.0, color='red', linestyle='--', linewidth=1, alpha=0.5)
ax4_twin.axvline(10.5, color='orange', linestyle='--', linewidth=1, alpha=0.5)

ax4.set_xlabel('Buffer Amount (%)', fontsize=11, fontweight='bold')
ax4.set_title('Basel III Capital Buffer Structure', fontsize=12, fontweight='bold')
ax4.grid(True, alpha=0.3, axis='x')

# Add value labels
for i, (bar, val, cum) in enumerate(zip(bars4, buffer_amounts, cumulative)):
    width = bar.get_width()
    ax4.text(width/2, bar.get_y() + bar.get_height()/2.,
             f'{val:.1f}%',
             ha='center', va='center', fontsize=9, fontweight='bold', color='white')
    ax4_twin.text(cum, i, f'{cum:.1f}%', ha='left', va='center', fontsize=8, 
                  bbox=dict(boxstyle='round', facecolor='lightblue', alpha=0.7))

plt.tight_layout()
display(fig)
plt.close(fig)

Stress Capital Buffer

The stress capital buffer is an additional capital requirement based on stress test results. Banks that perform poorly in stress tests must hold additional capital to provide a buffer against stress scenarios. This requirement creates incentives for banks to manage risk effectively and to prepare for extreme events.

The stress capital buffer is calculated based on the difference between a bank's capital ratio in a stress scenario and the minimum required ratio. If a bank's capital ratio would fall below the minimum in a stress scenario, the bank must hold additional capital equal to that shortfall. This ensures that banks can survive stress scenarios without falling below minimum capital requirements.

Python exercise

#| label: real-vs-nominal-rates
#| fig-cap: "Real vs. Nominal Interest Rates: r_real = r_nominal - π Relationship Over Time"
#| fig-width: 16
#| fig-height: 10
#| echo: false
#| warning: false

import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display

# Time periods (years)
years = np.arange(2000, 2024, 1)

# Simulate nominal interest rates (varying over time)
nominal_rates = 3.0 + 2.0 * np.sin((years - 2000) * np.pi / 8) + np.random.normal(0, 0.3, len(years))

# Simulate inflation rates (varying over time)
inflation_rates = 2.0 + 1.5 * np.sin((years - 2000) * np.pi / 6 + np.pi/4) + np.random.normal(0, 0.2, len(years))

# Calculate real rates: r_real = r_nominal - π
real_rates = nominal_rates - inflation_rates

# Create figure
fig, axes = plt.subplots(2, 2, figsize=(16, 12))
fig.suptitle('Real vs. Nominal Interest Rates: r_real = r_nominal - π Over Time', 
            fontsize=16, fontweight='bold')

# Plot 1: Nominal, Real, and Inflation Over Time
ax1 = axes[0, 0]
ax1.plot(years, nominal_rates, 'b-o', linewidth=2.5, markersize=6, 
        label='Nominal Interest Rate', alpha=0.8)
ax1.plot(years, real_rates, 'g-s', linewidth=2.5, markersize=6, 
        label='Real Interest Rate', alpha=0.8)
ax1.plot(years, inflation_rates, 'r-^', linewidth=2.5, markersize=6, 
        label='Inflation Rate', alpha=0.8)
ax1.axhline(y=0, color='black', linestyle='-', linewidth=1, alpha=0.5)
ax1.fill_between(years, 0, inflation_rates, alpha=0.2, color='red', label='Inflation Zone')
ax1.set_xlabel('Year', fontsize=12, fontweight='bold')
ax1.set_ylabel('Rate (%)', fontsize=12, fontweight='bold')
ax1.set_title('Interest Rates and Inflation Over Time', fontsize=13, fontweight='bold')
ax1.grid(True, alpha=0.3, linestyle='--')
ax1.legend(loc='best', fontsize=9)

# Add formula annotation
ax1.text(0.02, 0.98, 'Fisher Equation:\nr_real = r_nominal - π', 
        transform=ax1.transAxes, fontsize=11, fontweight='bold',
        bbox=dict(boxstyle='round', facecolor='yellow', alpha=0.8),
        verticalalignment='top', family='monospace')

# Plot 2: Relationship Between Nominal and Real Rates
ax2 = axes[0, 1]
scatter = ax2.scatter(nominal_rates, real_rates, c=inflation_rates, 
                     s=100, cmap='RdYlGn_r', alpha=0.7, edgecolors='black', linewidth=1.5)
# Add diagonal line showing r_nominal = r_real (when inflation = 0)
ax2.plot([0, 8], [0, 8], 'k--', linewidth=1.5, alpha=0.5, label='r_nominal = r_real (π=0)')
ax2.set_xlabel('Nominal Interest Rate (%)', fontsize=12, fontweight='bold')
ax2.set_ylabel('Real Interest Rate (%)', fontsize=12, fontweight='bold')
ax2.set_title('Real vs. Nominal Rate Relationship', fontsize=13, fontweight='bold')
ax2.grid(True, alpha=0.3, linestyle='--')
cbar = plt.colorbar(scatter, ax=ax2)
cbar.set_label('Inflation Rate (%)', fontsize=11, fontweight='bold')
ax2.legend(loc='best', fontsize=9)

# Plot 3: Real Rate Distribution
ax3 = axes[1, 0]
ax3.hist(real_rates, bins=15, color='green', alpha=0.7, edgecolor='black', linewidth=1.5)
ax3.axvline(x=np.mean(real_rates), color='red', linestyle='--', linewidth=2, 
           label=f'Mean: {np.mean(real_rates):.2f}%')
ax3.axvline(x=0, color='black', linestyle='-', linewidth=1, alpha=0.5)
ax3.set_xlabel('Real Interest Rate (%)', fontsize=12, fontweight='bold')
ax3.set_ylabel('Frequency', fontsize=12, fontweight='bold')
ax3.set_title('Distribution of Real Interest Rates', fontsize=13, fontweight='bold')
ax3.grid(True, alpha=0.3, linestyle='--', axis='y')
ax3.legend(loc='best', fontsize=9)

# Plot 4: Impact of Inflation on Real Returns
ax4 = axes[1, 1]
# Show how different inflation scenarios affect real returns for a fixed nominal rate
fixed_nominal = 5.0
inflation_scenarios = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8])
real_returns = fixed_nominal - inflation_scenarios

bars = ax4.barh(inflation_scenarios, real_returns, 
               color=plt.cm.RdYlGn_r(np.linspace(0.2, 0.8, len(inflation_scenarios))), 
               alpha=0.7, edgecolor='black', linewidth=1.5)
ax4.axvline(x=0, color='black', linestyle='-', linewidth=1.5)
ax4.set_xlabel('Real Interest Rate (%)', fontsize=12, fontweight='bold')
ax4.set_ylabel('Inflation Rate (%)', fontsize=12, fontweight='bold')
ax4.set_title(f'Real Return Impact: Fixed Nominal Rate = {fixed_nominal}%', 
             fontsize=13, fontweight='bold')
ax4.grid(True, alpha=0.3, linestyle='--', axis='x')

# Add value labels
for i, (bar, real) in enumerate(zip(bars, real_returns)):
    width = bar.get_width()
    ax4.text(width + 0.1 if width > 0 else width - 0.1, bar.get_y() + bar.get_height()/2,
            f'{real:.1f}%', ha='left' if width > 0 else 'right', va='center',
            fontsize=9, fontweight='bold')

plt.tight_layout()
display(fig)
plt.close(fig)

print(f"\n📊 **Real vs. Nominal Interest Rates Analysis**")
print(f"{'='*70}")
print(f"Formula: r_real = r_nominal - π")
print(f"  where r_real = Real interest rate (inflation-adjusted)")
print(f"        r_nominal = Nominal interest rate (stated rate)")
print(f"        π = Inflation rate")
print(f"{'='*70}")
print(f"Key Insights:")
print(f"  • When inflation > 0: Real rate < Nominal rate")
print(f"  • When inflation < 0 (deflation): Real rate > Nominal rate")
print(f"  • Real rates reflect true purchasing power of returns")
print(f"  • Economic decisions should be based on real rates")
print(f"{'='*70}")
print(f"Example: If nominal rate = 5% and inflation = 2%:")
print(f"  Real rate = 5% - 2% = 3%")
print(f"  Your purchasing power increases by 3%, not 5%")
print(f"{'='*70}")
print(f"✅ Real rates are more important for economic decisions")
print(f"✅ High inflation can make real rates negative even with positive nominal rates")

Risk-Weighted Assets (RWA)

Risk-weighted assets adjust asset values for risk, ensuring that riskier assets require more capital. RWA calculation methods vary by asset type. For credit risk, RWA is typically calculated using standardized approaches (with fixed risk weights) or internal ratings-based approaches (where banks use their own models to estimate risk weights).

For market risk, RWA is calculated based on VaR and stress VaR measures. For operational risk, RWA is calculated based on operational risk models or standardized approaches. These different approaches reflect the different characteristics of different risk types and the different measurement challenges they present.

RWA calculation is important because it directly affects capital requirements. Banks have incentives to reduce RWA, which they can do by reducing risk, by using more sophisticated models that might produce lower RWA estimates, or by shifting to lower-risk assets. Understanding these incentives helps explain bank behavior and the effects of capital regulation.

Python exercise

# Interactive Yield Curve Visualization
# Shows Normal, Inverted, Flat, and Steep yield curves with economic implications

# Create an interactive yield curve visualization with HTML5 Canvas and JavaScript
interactive_html = """
<div id="yield-curve-shapes" style="margin: 2em 0; padding: 1.5em; background: #ffffff; border: 1px solid #e5e7eb; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
    <h3 style="margin-top: 0; color: #1f2937; font-size: 1.25em; font-weight: 600;">Yield Curve Shapes: Economic Indicators</h3>
    <p style="color: #6b7280; margin-bottom: 1.5em;">Explore different yield curve shapes and their economic implications:</p>
    
    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1em; margin-bottom: 2em;">
        <div style="padding: 1em; background: #f9fafb; border-radius: 6px;">
            <label style="display: block; margin-bottom: 0.5em; font-weight: 500; color: #374151;">
                Curve Type:
            </label>
            <select id="curve_type" style="width: 100%; padding: 0.5em; border: 1px solid #d1d5db; border-radius: 4px; font-size: 0.9em;">
                <option value="normal">Normal (Upward)</option>
                <option value="inverted">Inverted (Downward)</option>
                <option value="flat">Flat</option>
                <option value="steep">Steep</option>
                <option value="all">All Curves (Comparison)</option>
            </select>
        </div>
        
        <div style="padding: 1em; background: #f9fafb; border-radius: 6px;">
            <label style="display: block; margin-bottom: 0.5em; font-weight: 500; color: #374151;">
                Short-term Rate (3mo):
            </label>
            <input type="range" id="short_rate" min="0" max="6" value="2" step="0.1" 
                   style="width: 100%; height: 8px; border-radius: 4px; background: #e5e7eb; outline: none;">
            <div style="text-align: center; margin-top: 0.5em;">
                <span id="short_rate_value" style="display: inline-block; padding: 0.5em 1em; background: #059669; color: white; font-weight: 600; font-size: 1em; border-radius: 6px; min-width: 60px;">2.0%</span>
            </div>
        </div>
        
        <div style="padding: 1em; background: #f9fafb; border-radius: 6px;">
            <label style="display: block; margin-bottom: 0.5em; font-weight: 500; color: #374151;">
                Long-term Rate (30yr):
            </label>
            <input type="range" id="long_rate" min="0" max="8" value="4.8" step="0.1"
                   style="width: 100%; height: 8px; border-radius: 4px; background: #e5e7eb; outline: none;">
            <div style="text-align: center; margin-top: 0.5em;">
                <span id="long_rate_value" style="display: inline-block; padding: 0.5em 1em; background: #dc2626; color: white; font-weight: 600; font-size: 1em; border-radius: 6px; min-width: 60px;">4.8%</span>
            </div>
        </div>
        
        <div style="padding: 1em; background: #f9fafb; border-radius: 6px;">
            <label style="display: block; margin-bottom: 0.5em; font-weight: 500; color: #374151;">
                Curve Steepness:
            </label>
            <input type="range" id="steepness" min="0.1" max="3" value="1" step="0.1"
                   style="width: 100%; height: 8px; border-radius: 4px; background: #e5e7eb; outline: none;">
            <div style="text-align: center; margin-top: 0.5em;">
                <span id="steepness_value" style="display: inline-block; padding: 0.5em 1em; background: #2563eb; color: white; font-weight: 600; font-size: 1em; border-radius: 6px; min-width: 60px;">1.0</span>
            </div>
        </div>
    </div>
    
    <div style="background: white; padding: 1.5em; border-radius: 6px; border: 1px solid #e5e7eb;">
        <canvas id="yieldCurveCanvas" width="700" height="700" style="width: 100%; max-width: 700px; height: 700px; border: 1px solid #e5e7eb; border-radius: 4px; display: block;"></canvas>
    </div>
    
    <div id="curve-analysis" style="margin-top: 1.5em; padding: 1.5em; background: #eff6ff; border-radius: 6px; border-left: 4px solid #2563eb;">
        <h4 style="margin: 0 0 0.5em 0; color: #1e40af; font-size: 1em; font-weight: 600;">Economic Analysis:</h4>
        <p id="analysis_text" style="margin: 0; color: #1e40af; font-size: 0.9em; line-height: 1.6;">
            Normal (upward-sloping) curve indicating expected economic growth.
        </p>
    </div>
</div>

<script>
(function() {
    console.log('[Yield Curve Shapes] Script starting...');
    
    const maturities = [0.25, 0.5, 1, 2, 3, 5, 7, 10, 20, 30];
    
    function initCanvas() {
        const canvas = document.getElementById('yieldCurveCanvas');
        if (!canvas) {
            console.error('[Yield Curve Shapes] Canvas not found');
            return;
        }
        
        const ctx = canvas.getContext('2d');
        if (!ctx) {
            console.error('[Yield Curve Shapes] Could not get 2D context');
            return;
        }
        
        // Set canvas size for high DPI displays
        const dpr = window.devicePixelRatio || 1;
        const baseWidth = 700;
        const baseHeight = 700;
        
        canvas.width = baseWidth * dpr;
        canvas.height = baseHeight * dpr;
        ctx.scale(dpr, dpr);
        canvas.style.width = baseWidth + 'px';
        canvas.style.height = baseHeight + 'px';
        
        console.log('[Yield Curve Shapes] Canvas initialized');
    }
    
    function calculateYields(curveType, shortRate, longRate, steepness) {
        const yields = [];
        
        for (const maturity of maturities) {
            let yield_val;
            
            if (curveType === 'normal') {
                // Normal: upward sloping, exponential interpolation
                yield_val = shortRate + (longRate - shortRate) * (1 - Math.exp(-maturity * steepness / 10));
            } else if (curveType === 'inverted') {
                // Inverted: downward sloping
                yield_val = longRate + (shortRate - longRate) * (1 - Math.exp(-maturity * steepness / 10));
            } else if (curveType === 'flat') {
                // Flat: constant yield
                yield_val = (shortRate + longRate) / 2;
            } else if (curveType === 'steep') {
                // Steep: very upward sloping
                yield_val = shortRate + (longRate - shortRate) * (1 - Math.exp(-maturity * steepness / 5));
            } else {
                // Default to normal
                yield_val = shortRate + (longRate - shortRate) * (1 - Math.exp(-maturity * steepness / 10));
            }
            
            yields.push(yield_val);
        }
        
        return yields;
    }
    
    function drawYieldCurve(curveType, shortRate, longRate, steepness) {
        const canvas = document.getElementById('yieldCurveCanvas');
        if (!canvas) return;
        
        const ctx = canvas.getContext('2d');
        if (!ctx) return;
        
        const dpr = window.devicePixelRatio || 1;
        const width = canvas.width / dpr;
        const height = canvas.height / dpr;
        
        // Clear canvas
        ctx.clearRect(0, 0, width, height);
        
        // Set up axes
        const padding = { top: 50, right: 40, bottom: 70, left: 70 };
        const plotWidth = width - padding.left - padding.right;
        const plotHeight = height - padding.top - padding.bottom;
        
        const maxMaturity = 30;
        const minYield = Math.max(0, Math.min(shortRate, longRate) - 1);
        const maxYield = Math.min(10, Math.max(shortRate, longRate) + 1);
        const yieldRange = maxYield - minYield;
        
        // Draw grid
        ctx.strokeStyle = '#e5e7eb';
        ctx.lineWidth = 1;
        for (let i = 0; i <= 10; i++) {
            const y = padding.top + (plotHeight * i / 10);
            ctx.beginPath();
            ctx.moveTo(padding.left, y);
            ctx.lineTo(width - padding.right, y);
            ctx.stroke();
        }
        for (let i = 0; i <= 6; i++) {
            const x = padding.left + (plotWidth * i / 6);
            ctx.beginPath();
            ctx.moveTo(x, padding.top);
            ctx.lineTo(x, height - padding.bottom);
            ctx.stroke();
        }
        
        // Draw axes
        ctx.strokeStyle = '#374151';
        ctx.lineWidth = 2;
        ctx.beginPath();
        ctx.moveTo(padding.left, padding.top);
        ctx.lineTo(padding.left, height - padding.bottom);
        ctx.lineTo(width - padding.right, height - padding.bottom);
        ctx.stroke();
        
        if (curveType === 'all') {
            // Draw all four curve types
            const curves = [
                { type: 'normal', color: '#2563eb', label: 'Normal' },
                { type: 'inverted', color: '#dc2626', label: 'Inverted' },
                { type: 'flat', color: '#f59e0b', label: 'Flat' },
                { type: 'steep', color: '#059669', label: 'Steep' }
            ];
            
            // Use preset values for comparison
            const presetValues = {
                normal: { short: 2.0, long: 4.8, steep: 1.0 },
                inverted: { short: 5.0, long: 2.2, steep: 1.0 },
                flat: { short: 3.5, long: 3.5, steep: 1.0 },
                steep: { short: 1.5, long: 6.2, steep: 2.0 }
            };
            
            curves.forEach((curve, idx) => {
                const preset = presetValues[curve.type];
                const yields = calculateYields(curve.type, preset.short, preset.long, preset.steepness);
                
                ctx.strokeStyle = curve.color;
                ctx.lineWidth = 3;
                ctx.beginPath();
                
                for (let i = 0; i < maturities.length; i++) {
                    const x = padding.left + (maturities[i] / maxMaturity) * plotWidth;
                    const y = height - padding.bottom - ((yields[i] - minYield) / yieldRange) * plotHeight;
                    if (i === 0) {
                        ctx.moveTo(x, y);
                    } else {
                        ctx.lineTo(x, y);
                    }
                }
                ctx.stroke();
                
                // Draw points
                ctx.fillStyle = curve.color;
                for (let i = 0; i < maturities.length; i++) {
                    const x = padding.left + (maturities[i] / maxMaturity) * plotWidth;
                    const y = height - padding.bottom - ((yields[i] - minYield) / yieldRange) * plotHeight;
                    ctx.beginPath();
                    ctx.arc(x, y, 4, 0, 2 * Math.PI);
                    ctx.fill();
                }
            });
            
            // Legend
            ctx.font = '12px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
            ctx.textAlign = 'left';
            let legendY = padding.top + 20;
            curves.forEach((curve) => {
                ctx.fillStyle = curve.color;
                ctx.fillRect(width - padding.right - 100, legendY, 15, 3);
                ctx.fillStyle = '#374151';
                ctx.fillText(curve.label, width - padding.right - 80, legendY + 8);
                legendY += 20;
            });
        } else {
            // Draw single curve
            const yields = calculateYields(curveType, shortRate, longRate, steepness);
            
            let curveColor = '#2563eb';
            if (curveType === 'inverted') curveColor = '#dc2626';
            else if (curveType === 'flat') curveColor = '#f59e0b';
            else if (curveType === 'steep') curveColor = '#059669';
            
            ctx.strokeStyle = curveColor;
            ctx.lineWidth = 3;
            ctx.beginPath();
            
            for (let i = 0; i < maturities.length; i++) {
                const x = padding.left + (maturities[i] / maxMaturity) * plotWidth;
                const y = height - padding.bottom - ((yields[i] - minYield) / yieldRange) * plotHeight;
                if (i === 0) {
                    ctx.moveTo(x, y);
                } else {
                    ctx.lineTo(x, y);
                }
            }
            ctx.stroke();
            
            // Fill area under curve
            ctx.fillStyle = curveColor;
            ctx.globalAlpha = 0.2;
            ctx.beginPath();
            ctx.moveTo(padding.left, height - padding.bottom);
            for (let i = 0; i < maturities.length; i++) {
                const x = padding.left + (maturities[i] / maxMaturity) * plotWidth;
                const y = height - padding.bottom - ((yields[i] - minYield) / yieldRange) * plotHeight;
                ctx.lineTo(x, y);
            }
            ctx.lineTo(width - padding.right, height - padding.bottom);
            ctx.closePath();
            ctx.fill();
            ctx.globalAlpha = 1.0;
            
            // Draw points
            ctx.fillStyle = curveColor;
            for (let i = 0; i < maturities.length; i++) {
                const x = padding.left + (maturities[i] / maxMaturity) * plotWidth;
                const y = height - padding.bottom - ((yields[i] - minYield) / yieldRange) * plotHeight;
                ctx.beginPath();
                ctx.arc(x, y, 5, 0, 2 * Math.PI);
                ctx.fill();
            }
        }
        
        // Draw labels
        ctx.fillStyle = '#374151';
        ctx.font = '12px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
        ctx.textAlign = 'center';
        
        // X-axis labels
        const xLabels = [0, 5, 10, 15, 20, 25, 30];
        xLabels.forEach(maturity => {
            const x = padding.left + (maturity / maxMaturity) * plotWidth;
            ctx.fillText(maturity + 'Y', x, height - padding.bottom + 20);
        });
        
        // Y-axis labels
        ctx.textAlign = 'right';
        for (let i = 0; i <= 5; i++) {
            const yield_val = minYield + (yieldRange * i / 5);
            const y = height - padding.bottom - (plotHeight * i / 5);
            ctx.fillText(yield_val.toFixed(1) + '%', padding.left - 10, y + 4);
        }
        
        // Axis titles
        ctx.textAlign = 'center';
        ctx.font = '14px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
        ctx.fillStyle = '#1f2937';
        ctx.fillText('Maturity (Years)', width / 2, height - 10);
        
        ctx.save();
        ctx.translate(20, height / 2);
        ctx.rotate(-Math.PI / 2);
        ctx.fillText('Yield (%)', 0, 0);
        ctx.restore();
        
        // Title
        const titles = {
            normal: 'Normal Yield Curve (Upward Sloping)',
            inverted: 'Inverted Yield Curve (Downward Sloping)',
            flat: 'Flat Yield Curve',
            steep: 'Steep Yield Curve',
            all: 'Yield Curve Comparison'
        };
        ctx.font = 'bold 16px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
        ctx.fillText(titles[curveType] || 'Yield Curve', width / 2, 30);
        
        // Update analysis
        updateAnalysis(curveType, shortRate, longRate);
    }
    
    function updateAnalysis(curveType, shortRate, longRate) {
        const analysisEl = document.getElementById('analysis_text');
        if (!analysisEl) return;
        
        const spread = longRate - shortRate;
        let analysis = '';
        let bgColor = '#eff6ff';
        let borderColor = '#2563eb';
        
        if (curveType === 'all') {
            analysis = 'Compare all four yield curve shapes. Normal curves indicate healthy growth, inverted curves warn of recession, flat curves show uncertainty, and steep curves signal strong growth expectations.';
        } else if (curveType === 'normal') {
            if (spread > 1.5) {
                analysis = 'Steep normal curve - Strong economic growth expected, rising inflation expectations. Long-term rates significantly exceed short-term rates, indicating healthy economic expansion.';
            } else if (spread > 0.5) {
                analysis = 'Normal (upward-sloping) curve - Expected economic growth and moderate inflation. Reflects time preference, inflation expectations, and risk premium.';
            } else {
                analysis = 'Slightly upward curve - Mild growth expectations. The curve is flattening, which may indicate economic transition.';
            }
        } else if (curveType === 'inverted') {
            analysis = '⚠️ Inverted yield curve - Recession warning signal. Short-term rates exceed long-term rates, indicating expected rate cuts, economic slowdown, and recession risk. Historically, inverted curves have preceded recessions.';
            bgColor = '#fef2f2';
            borderColor = '#dc2626';
        } else if (curveType === 'flat') {
            analysis = 'Flat yield curve - Transition period or economic uncertainty. All maturities have similar yields, indicating policy uncertainty, economic transition, or market indecision.';
            bgColor = '#fffbeb';
            borderColor = '#f59e0b';
        } else if (curveType === 'steep') {
            analysis = 'Steep yield curve - Very strong economic growth expectations. Large spread between short and long-term rates indicates robust expansion, high inflation expectations, and strong demand for long-term capital.';
            bgColor = '#f0fdf4';
            borderColor = '#059669';
        }
        
        analysisEl.textContent = analysis;
        const analysisDiv = document.getElementById('curve-analysis');
        if (analysisDiv) {
            analysisDiv.style.background = bgColor;
            analysisDiv.style.borderLeftColor = borderColor;
        }
    }
    
    // Make updateYieldCurve globally accessible
    window.updateYieldCurveShapes = function() {
        const curveTypeEl = document.getElementById('curve_type');
        const shortRateEl = document.getElementById('short_rate');
        const longRateEl = document.getElementById('long_rate');
        const steepnessEl = document.getElementById('steepness');
        
        if (!curveTypeEl || !shortRateEl || !longRateEl || !steepnessEl) {
            console.error('[Yield Curve Shapes] Control elements not found');
            return;
        }
        
        const curveType = curveTypeEl.value;
        const shortRate = parseFloat(shortRateEl.value);
        const longRate = parseFloat(longRateEl.value);
        const steepness = parseFloat(steepnessEl.value);
        
        // Update value badges
        const shortRateValueEl = document.getElementById('short_rate_value');
        const longRateValueEl = document.getElementById('long_rate_value');
        const steepnessValueEl = document.getElementById('steepness_value');
        
        if (shortRateValueEl) shortRateValueEl.textContent = shortRate.toFixed(1) + '%';
        if (longRateValueEl) longRateValueEl.textContent = longRate.toFixed(1) + '%';
        if (steepnessValueEl) steepnessValueEl.textContent = steepness.toFixed(1);
        
        drawYieldCurve(curveType, shortRate, longRate, steepness);
    };
    
    // Initialize
    function tryInit() {
        const canvas = document.getElementById('yieldCurveCanvas');
        const curveTypeEl = document.getElementById('curve_type');
        const shortRateEl = document.getElementById('short_rate');
        const longRateEl = document.getElementById('long_rate');
        const steepnessEl = document.getElementById('steepness');
        
        if (canvas && curveTypeEl && shortRateEl && longRateEl && steepnessEl) {
            console.log('[Yield Curve Shapes] All elements found, initializing...');
            initCanvas();
            window.updateYieldCurveShapes();
            
            // Attach event listeners
            curveTypeEl.addEventListener('change', window.updateYieldCurveShapes);
            shortRateEl.addEventListener('input', window.updateYieldCurveShapes);
            longRateEl.addEventListener('input', window.updateYieldCurveShapes);
            steepnessEl.addEventListener('input', window.updateYieldCurveShapes);
            
            console.log('[Yield Curve Shapes] Initialization complete!');
            return true;
        }
        return false;
    }
    
    // Try multiple times to ensure elements are available
    if (!tryInit()) {
        setTimeout(function() {
            if (!tryInit()) {
                setTimeout(tryInit, 200);
            }
        }, 50);
    }
})();
</script>
"""

# Write HTML directly to stdout with Pyodide markers
import sys
sys.stdout.write(f"[HTML_CONTENT]{interactive_html}[/HTML_CONTENT]\n")
sys.stdout.flush()

Summary: Integrated Risk Management

Effective banking risk management requires integrating multiple risk types, multiple measurement approaches, and multiple management techniques. Credit risk, market risk, and operational risk interact in complex ways, and managing them in isolation is insufficient. Banks must understand how risks interact, how they aggregate at the portfolio level, and how they affect the bank's overall risk profile.

The regulatory capital framework provides a common language and common standards for risk management across banks and jurisdictions. However, regulatory requirements are minimum standards - effective risk management requires going beyond regulatory minimums to ensure that banks can survive not just normal conditions but also stress scenarios.

As banking continues to evolve - with new products, new technologies, and new risks - risk management must continue to evolve as well. The fundamental principles of risk management - identify, measure, manage, and monitor - remain constant, but the specific techniques and tools must adapt to changing conditions. Understanding these principles and their applications provides a foundation for understanding how banks function and how banking systems remain stable.

In Module 2: Banking Fundamentals

  1. Introduction
  2. Banking System Overview: The Foundation of Modern Finance
  3. Central Banks and Monetary Policy: The Managers of Money
  4. Commercial Banking Operations: The Engine of Credit
  5. Interest Rates and Yield Curves: The Price of Money and Time
  6. Money Markets: Short-Term Funding and Liquidity
  7. Credit and Lending: The Art and Science of Risk Assessment
  8. Banking Risk Management
  9. Future of Banking
  10. End-of-Module Assessment