Banking System Overview: The Foundation of Modern Finance

30 minbeginner

1. Banking System Overview: The Foundation of Modern Finance

Banking is one of the oldest and most fundamental institutions in human civilization. From the earliest money changers in ancient temples to the sophisticated global banking networks of today, banks have served as the critical intermediaries that enable economic activity. Understanding banking is essential for understanding financial markets, because banks are not just participants in markets - they are the infrastructure that makes markets possible.

What Are Banks? The Economic Functions

At its core, a bank is a financial institution that accepts deposits and makes loans. But this simple definition belies the complex and crucial role that banks play in the economy. Banks are not just financial intermediaries - they are creators of money, managers of risk, facilitators of payments, and engines of economic growth.

The most fundamental function of banks is financial intermediation - connecting savers (who have money but don't need it immediately) with borrowers (who need money but don't have it). This intermediation serves several crucial economic functions:

Maturity Transformation is perhaps the most important function. Savers typically want short-term, liquid deposits - they want to be able to access their money quickly if needed. Borrowers typically need long-term, illiquid loans - they need time to invest the money and generate returns. Banks bridge this gap by accepting short-term deposits and making long-term loans. This transformation is crucial for economic growth, because it allows long-term investments to be funded with short-term savings.

Risk Transformation occurs as banks diversify risk. Individual savers face significant risk if they lend directly to a single borrower - if that borrower defaults, the saver loses everything. Banks reduce this risk by pooling deposits from many savers and lending to many borrowers. If one borrower defaults, the bank's diversified portfolio absorbs the loss, and individual depositors are protected. This risk diversification allows savings to flow to productive investments that would be too risky for individual savers.

Liquidity Provision is essential for economic activity. Banks provide liquidity by allowing depositors to withdraw their money on demand, even though the bank has lent that money out for long terms. This is possible because banks maintain reserves and because not all depositors withdraw at once. The ability to provide liquidity while holding illiquid assets is a defining characteristic of banking, but it also creates vulnerability - if too many depositors demand their money at once (a bank run), the bank may be unable to meet all demands.

Payment Services are crucial infrastructure that banks provide. Every time you use a credit card, write a check, or transfer money electronically, banks are facilitating the transaction. The payment system is so fundamental to modern economies that it's often taken for granted, but without banks to process payments, commerce would grind to a halt. Banks operate the clearing and settlement systems that allow money to move between accounts, between banks, and between countries.

Money Creation is perhaps the most surprising function of banks. When a bank makes a loan, it doesn't necessarily lend out existing deposits - it creates new money. Here's how: when Bank A lends $100,000 to a borrower, it credits the borrower's account with $100,000. This $100,000 didn't exist before - the bank created it. The borrower spends this money, and it ends up as deposits in other banks, which can then lend it out again, creating more money. This process of money creation is crucial for economic growth, but it also creates the potential for inflation and financial instability if not properly managed.

The Banking System Structure

The banking system is not monolithic - it consists of different types of banks serving different functions:

Central Banks are the apex of the banking system. They don't serve individual customers - instead, they serve as bankers to commercial banks and as managers of the monetary system. Central banks control the money supply, set interest rates, supervise banks, and act as lenders of last resort during crises. Examples include the Federal Reserve (United States), the European Central Bank, the Bank of England, and the Bank of Japan.

Commercial Banks are the banks that most people interact with. They accept deposits from individuals and businesses, make loans, and provide payment services. Commercial banks range from small community banks serving local areas to massive global banks serving millions of customers worldwide. They are the primary intermediaries between savers and borrowers.

Investment Banks are different from commercial banks. They don't typically accept deposits from individuals - instead, they help companies raise capital by issuing securities, provide advice on mergers and acquisitions, trade securities, and manage assets. The distinction between commercial and investment banks has blurred over time, with many large banks operating both types of businesses.

Credit Unions and Savings Banks are depository institutions similar to commercial banks but organized differently. Credit unions are member-owned cooperatives, while savings banks are often mutual organizations. They typically serve specific communities or groups and may have different regulatory requirements than commercial banks.

Shadow Banks are institutions that perform banking-like functions but are not traditional banks. Money market funds, hedge funds, and certain types of investment companies can act like banks by accepting short-term deposits (in the form of investments) and making longer-term loans or investments. Shadow banking has grown significantly and poses regulatory challenges because these institutions are not subject to the same regulations as traditional banks.

The Balance Sheet of a Bank

Understanding a bank's balance sheet is crucial for understanding how banks operate and what risks they face. A bank's balance sheet is fundamentally different from a typical company's balance sheet because the bank's assets (loans) are funded primarily by liabilities (deposits) rather than equity.

Assets on a bank's balance sheet include:

  • Reserves: Cash held at the bank and deposits at the central bank. Reserves are required by regulation and provide liquidity.
  • Loans: The primary earning asset for most banks. Loans include mortgages, business loans, consumer loans, and credit card receivables.
  • Securities: Government bonds, corporate bonds, and other securities that banks hold for liquidity and income.
  • Other Assets: Physical assets like buildings and equipment, as well as intangible assets.

Liabilities include:

  • Deposits: The primary source of funding for banks. Deposits include checking accounts, savings accounts, and certificates of deposit (CDs).
  • Borrowings: Money borrowed from other banks, the central bank, or through issuing bonds.
  • Other Liabilities: Various obligations including payments due, deferred taxes, and other commitments.

Equity represents the bank's capital - the difference between assets and liabilities. Bank capital serves as a buffer against losses. If loans default, capital absorbs the losses before depositors are affected. This is why capital requirements are crucial for bank safety.

The key insight from a bank's balance sheet is leverage - banks operate with very high leverage ratios. A typical bank might have capital equal to only 10% of assets, meaning it's leveraged 10-to-1. This high leverage allows banks to earn high returns on equity, but it also makes them vulnerable to losses. A decline in asset values of just 10% could wipe out all capital.

Let's visualize a typical bank balance sheet structure:

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()

Python exercise

#| label: bank-balance-sheet
#| fig-cap: "Bank Balance Sheet Structure: Assets, Liabilities, and Leverage"
#| fig-width: 14
#| fig-height: 8
#| echo: false
#| warning: false

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

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

# Example bank balance sheet (in billions)
total_assets = 100
reserves = 5
loans = 70
securities = 20
other_assets = 5

deposits = 85
borrowings = 5
other_liabilities = 2
equity = 8  # 8% capital ratio

# Create figure
fig, axes = plt.subplots(1, 2, figsize=(16, 8))
fig.suptitle('Bank Balance Sheet Structure and Leverage', fontsize=16, fontweight='bold')

# Plot 1: Assets Breakdown
ax1 = axes[0]
assets_labels = ['Reserves\n(Liquidity)', 'Loans\n(Earning Assets)', 'Securities\n(Liquid Assets)', 'Other Assets']
assets_values = [reserves, loans, securities, other_assets]
colors_assets = ['#90EE90', '#4169E1', '#FFD700', '#D3D3D3']

bars1 = ax1.barh(assets_labels, assets_values, color=colors_assets, alpha=0.8, edgecolor='black', linewidth=1.5)
ax1.set_xlabel('Amount ($ Billions)', fontsize=12, fontweight='bold')
ax1.set_title('Assets Side', fontsize=13, fontweight='bold')
ax1.grid(True, alpha=0.3, linestyle='--', axis='x')
ax1.set_xlim(0, 100)

# Add value labels
for i, (bar, val) in enumerate(zip(bars1, assets_values)):
    width = bar.get_width()
    ax1.text(width + 1, bar.get_y() + bar.get_height()/2, 
             f'${val:.1f}B\n({val/total_assets*100:.1f}%)',
             ha='left', va='center', fontsize=10, fontweight='bold')

# Plot 2: Liabilities and Equity Breakdown
ax2 = axes[1]
liab_labels = ['Deposits\n(Primary Funding)', 'Borrowings\n(Wholesale Funding)', 'Other Liabilities', 'Equity\n(Capital)']
liab_values = [deposits, borrowings, other_liabilities, equity]
colors_liab = ['#87CEEB', '#FF6347', '#D3D3D3', '#32CD32']

bars2 = ax2.barh(liab_labels, liab_values, color=colors_liab, alpha=0.8, edgecolor='black', linewidth=1.5)
ax2.set_xlabel('Amount ($ Billions)', fontsize=12, fontweight='bold')
ax2.set_title('Liabilities & Equity Side', fontsize=13, fontweight='bold')
ax2.grid(True, alpha=0.3, linestyle='--', axis='x')
ax2.set_xlim(0, 100)

# Add value labels
for i, (bar, val) in enumerate(zip(bars2, liab_values)):
    width = bar.get_width()
    pct = val/total_assets*100 if val != equity else equity/total_assets*100
    ax2.text(width + 1, bar.get_y() + bar.get_height()/2, 
             f'${val:.1f}B\n({pct:.1f}%)',
             ha='left', va='center', fontsize=10, fontweight='bold')

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

# Calculate key metrics
leverage_ratio = total_assets / equity
loan_to_deposit_ratio = loans / deposits
reserve_ratio = reserves / deposits

print(f"\n📊 **Bank Balance Sheet Analysis**")
print(f"{'='*60}")
print(f"Total Assets:           ${total_assets:.1f} billion")
print(f"Total Liabilities:      ${deposits + borrowings + other_liabilities:.1f} billion")
print(f"Equity (Capital):       ${equity:.1f} billion ({equity/total_assets*100:.1f}%)")
print(f"{'='*60}")
print(f"Key Ratios:")
print(f"  Leverage Ratio:       {leverage_ratio:.1f}:1 (Assets/Equity)")
print(f"  Capital Ratio:        {equity/total_assets*100:.1f}% (Equity/Assets)")
print(f"  Loan-to-Deposit:      {loan_to_deposit_ratio:.2f} ({loans/deposits*100:.1f}%)")
print(f"  Reserve Ratio:        {reserve_ratio:.2f} ({reserves/deposits*100:.1f}%)")
print(f"{'='*60}")
print(f"Risk Implications:")
print(f"  • High leverage ({leverage_ratio:.1f}:1) means ${equity/total_assets*100:.1f}% loss could wipe out capital")
print(f"  • Maturity mismatch: Short-term deposits fund long-term loans")
print(f"  • Liquidity: ${reserves:.1f}B reserves provide buffer for withdrawals")

Now let's visualize how leverage affects a bank's return on equity (ROE) and risk - the leverage multiplier effect:

Python exercise

#| label: leverage-ratio-impact
#| fig-cap: "Leverage Ratio Impact: How Leverage Affects ROE and Risk (Leverage Multiplier Effect)"
#| fig-width: 16
#| fig-height: 10
#| echo: false
#| warning: false

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

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

# Bank parameters
asset_base = 100  # Base assets
roa_base = 0.015  # Return on Assets: 1.5%
cost_of_debt = 0.03  # Cost of debt: 3%

# Different equity levels (capital ratios)
equity_ratios = np.array([0.05, 0.08, 0.10, 0.12, 0.15, 0.20])  # 5% to 20%
equity_amounts = asset_base * equity_ratios
debt_amounts = asset_base - equity_amounts
leverage_ratios = asset_base / equity_amounts

# Calculate ROE for different scenarios
# ROE = (ROA × Assets - Cost of Debt × Debt) / Equity
# ROE = ROA × (Assets/Equity) - Cost of Debt × (Debt/Equity)
# ROE = ROA × Leverage - Cost of Debt × (Leverage - 1)

roes = []
for eq_ratio in equity_ratios:
    eq_amt = asset_base * eq_ratio
    debt_amt = asset_base - eq_amt
    leverage = asset_base / eq_amt
    
    # Net income = ROA × Assets - Cost of Debt × Debt
    net_income = roa_base * asset_base - cost_of_debt * debt_amt
    roe = net_income / eq_amt
    roes.append(roe)

roes = np.array(roes)

# Calculate risk (volatility of ROE)
# Higher leverage amplifies both returns and risk
# Risk of ROE = Leverage × Risk of ROA (assuming debt is risk-free)
roa_risk = 0.02  # 2% volatility in ROA
roe_risks = leverage_ratios * roa_risk

# Calculate loss that would wipe out capital
loss_to_wipeout = equity_ratios * 100  # As percentage of assets

# Create figure with multiple subplots
fig, axes = plt.subplots(2, 2, figsize=(16, 12))
fig.suptitle('Leverage Ratio Impact: ROE and Risk Analysis', fontsize=16, fontweight='bold')

# Plot 1: ROE vs. Leverage Ratio
ax1 = axes[0, 0]
ax1.plot(leverage_ratios, roes * 100, 'b-o', linewidth=3, markersize=10, label='ROE', alpha=0.8)
ax1.axhline(y=roa_base * 100, color='red', linestyle='--', linewidth=2, 
           label=f'ROA: {roa_base*100:.1f}%', alpha=0.7)
ax1.set_xlabel('Leverage Ratio (Assets/Equity)', fontsize=12, fontweight='bold')
ax1.set_ylabel('Return on Equity (ROE, %)', fontsize=12, fontweight='bold')
ax1.set_title('Leverage Multiplier Effect: ROE vs. Leverage', fontsize=13, fontweight='bold')
ax1.grid(True, alpha=0.3, linestyle='--')
ax1.legend(fontsize=10)
ax1.set_xlim(4, 21)

# Add annotations
for lev, roe in zip(leverage_ratios[:3], roes[:3] * 100):
    ax1.annotate(f'ROE: {roe:.1f}%\nLev: {lev:.1f}x', 
                xy=(lev, roe), xytext=(lev + 2, roe + 2),
                arrowprops=dict(arrowstyle='->', color='blue', lw=1.5),
                fontsize=9, fontweight='bold',
                bbox=dict(boxstyle='round', facecolor='lightblue', alpha=0.8))

# Plot 2: Risk Amplification
ax2 = axes[0, 1]
ax2.plot(leverage_ratios, roe_risks * 100, 'r-s', linewidth=3, markersize=10, label='ROE Risk', alpha=0.8)
ax2.axhline(y=roa_risk * 100, color='blue', linestyle='--', linewidth=2, 
           label=f'ROA Risk: {roa_risk*100:.1f}%', alpha=0.7)
ax2.set_xlabel('Leverage Ratio (Assets/Equity)', fontsize=12, fontweight='bold')
ax2.set_ylabel('ROE Risk (Volatility, %)', fontsize=12, fontweight='bold')
ax2.set_title('Leverage Amplifies Risk: ROE Volatility vs. Leverage', fontsize=13, fontweight='bold')
ax2.grid(True, alpha=0.3, linestyle='--')
ax2.legend(fontsize=10)
ax2.set_xlim(4, 21)

# Add annotation
ax2.annotate('Higher leverage = Higher risk\nLeverage multiplies both returns AND risk', 
            xy=(leverage_ratios[0], roe_risks[0] * 100), xytext=(10, 15),
            arrowprops=dict(arrowstyle='->', color='red', lw=2),
            fontsize=10, fontweight='bold',
            bbox=dict(boxstyle='round', facecolor='lightcoral', alpha=0.8))

# Plot 3: Risk-Return Trade-off
ax3 = axes[1, 0]
scatter = ax3.scatter(roe_risks * 100, roes * 100, s=300, c=leverage_ratios, 
                      cmap='viridis', alpha=0.7, edgecolors='black', linewidth=2)
ax3.set_xlabel('ROE Risk (Volatility, %)', fontsize=12, fontweight='bold')
ax3.set_ylabel('Return on Equity (ROE, %)', fontsize=12, fontweight='bold')
ax3.set_title('Risk-Return Trade-off: Higher Leverage = Higher Risk & Return', 
             fontsize=13, fontweight='bold')
ax3.grid(True, alpha=0.3, linestyle='--')

# Add colorbar
cbar = plt.colorbar(scatter, ax=ax3)
cbar.set_label('Leverage Ratio', fontsize=11, fontweight='bold')

# Add labels for each point
for lev, risk, roe in zip(leverage_ratios, roe_risks * 100, roes * 100):
    ax3.annotate(f'{lev:.1f}x', (risk, roe), fontsize=9, fontweight='bold',
                ha='center', va='center', color='white')

# Plot 4: Loss to Wipeout Capital
ax4 = axes[1, 1]
bars = ax4.barh(range(len(equity_ratios)), loss_to_wipeout, 
                color='red', alpha=0.7, edgecolor='black', linewidth=1.5)
ax4.set_yticks(range(len(equity_ratios)))
ax4.set_yticklabels([f'{eq*100:.0f}%\n({lev:.1f}x)' for eq, lev in zip(equity_ratios, leverage_ratios)])
ax4.set_xlabel('Asset Loss Required to Wipe Out Capital (%)', fontsize=12, fontweight='bold')
ax4.set_ylabel('Capital Ratio (Leverage Ratio)', fontsize=12, fontweight='bold')
ax4.set_title('Capital Buffer: Loss Capacity Before Insolvency', fontsize=13, fontweight='bold')
ax4.grid(True, alpha=0.3, linestyle='--', axis='x')
ax4.invert_yaxis()

# Add value labels
for i, (bar, loss) in enumerate(zip(bars, loss_to_wipeout)):
    width = bar.get_width()
    ax4.text(width + 0.5, bar.get_y() + bar.get_height()/2,
            f'{loss:.1f}%', ha='left', va='center', fontsize=10, fontweight='bold')

# Add warning zone
ax4.axvline(x=10, color='orange', linestyle='--', linewidth=2, alpha=0.7, 
           label='Typical Market Volatility (~10%)')
ax4.legend(fontsize=9)

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

# Create summary table visualization
fig2, ax = plt.subplots(figsize=(14, 6))
fig2.suptitle('Leverage Impact Summary: Key Metrics Comparison', fontsize=14, fontweight='bold')

# Create table data
table_data = []
headers = ['Capital\nRatio', 'Leverage\nRatio', 'ROE (%)', 'ROE Risk\n(%)', 'Loss to\nWipeout (%)']
for eq_ratio, lev, roe, risk, loss in zip(equity_ratios, leverage_ratios, 
                                          roes * 100, roe_risks * 100, loss_to_wipeout):
    table_data.append([f'{eq_ratio*100:.0f}%', f'{lev:.1f}x', f'{roe:.1f}%', 
                      f'{risk:.1f}%', f'{loss:.1f}%'])

# Create table
table = ax.table(cellText=table_data, colLabels=headers, cellLoc='center', loc='center',
                colWidths=[0.15, 0.15, 0.15, 0.15, 0.15])
table.auto_set_font_size(False)
table.set_fontsize(10)
table.scale(1, 2)

# Style header row
for i in range(len(headers)):
    table[(0, i)].set_facecolor('#4CAF50')
    table[(0, i)].set_text_props(weight='bold', color='white')

# Color code rows by leverage (higher leverage = darker)
for i, lev in enumerate(leverage_ratios, 1):
    intensity = min(0.9, 0.3 + (lev - 5) / 20)
    for j in range(len(headers)):
        table[(i, j)].set_facecolor(plt.cm.Reds(intensity))

ax.axis('off')
plt.tight_layout()
display(fig2)
plt.close(fig2)

print(f"\n📊 **Leverage Ratio Impact Analysis**")
print(f"{'='*70}")
print(f"Base Parameters:")
print(f"  Return on Assets (ROA):     {roa_base*100:.2f}%")
print(f"  Cost of Debt:               {cost_of_debt*100:.2f}%")
print(f"  ROA Risk (Volatility):     {roa_risk*100:.2f}%")
print(f"{'='*70}")
print(f"Leverage Impact:")
print(f"{'Capital':<10} {'Leverage':<10} {'ROE':<10} {'ROE Risk':<12} {'Loss to Wipeout':<15}")
print(f"{'Ratio':<10} {'Ratio':<10} {'(%)':<10} {'(%)':<12} {'(%)':<15}")
print(f"{'-'*70}")
for eq, lev, roe, risk, loss in zip(equity_ratios, leverage_ratios, 
                                    roes * 100, roe_risks * 100, loss_to_wipeout):
    print(f"{eq*100:>6.0f}%     {lev:>6.1f}x     {roe:>7.1f}%     {risk:>8.1f}%     {loss:>10.1f}%")
print(f"{'='*70}")
print(f"Key Insights:")
print(f"  • Leverage multiplies ROE: ROE = ROA × Leverage - Cost × (Leverage - 1)")
print(f"  • Leverage amplifies risk: ROE Risk = Leverage × ROA Risk")
print(f"  • Higher leverage = Higher returns BUT higher risk")
print(f"  • Lower capital ratio = Less buffer against losses")
print(f"  • At 5% capital: Only 5% asset loss wipes out all equity")

Banking Risks

Banks face several types of risk that are crucial to understand:

Credit Risk is the risk that borrowers will default on their loans. This is perhaps the most fundamental risk that banks face. Banks manage credit risk through careful underwriting, diversification, collateral, and loan loss reserves.

Liquidity Risk is the risk that the bank won't have enough cash to meet withdrawal demands or other obligations. Banks manage liquidity risk by maintaining reserves, holding liquid securities, and having access to funding sources like the central bank's discount window.

Interest Rate Risk arises from the mismatch between the maturity of assets and liabilities. Banks typically have long-term assets (loans) funded by short-term liabilities (deposits). If interest rates rise, the cost of funding increases while the income from existing loans stays fixed, squeezing bank profitability.

Market Risk is the risk that securities held by the bank will decline in value. Banks manage this risk through diversification and hedging.

Operational Risk includes risks from fraud, system failures, legal issues, and other operational problems. This risk has become more important as banking has become more complex and technology-dependent.

Understanding these risks is crucial because they explain why banking is heavily regulated and why banks need capital. The 2008 financial crisis demonstrated what happens when these risks are not properly managed - banks failed, credit froze, and the economy suffered severe damage.


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