SECTION 1: LEARNING OBJECTIVES

By the end of this lesson, you will be able to:

  • Define sustainable banking and its regulatory drivers (ESG, TCFD, EU Taxonomy).

  • Design green lending products and carbon accounting frameworks.

  • Implement data pipelines for ESG data aggregation and reporting.

  • Build a carbon footprint scoring model for customers and portfolios.

  • Understand the role of digital technology in enabling green finance.


SECTION 2: THE RISE OF SUSTAINABLE BANKING

2.1 Why Sustainable Banking Matters Now

 
 
Driver Description Banking Impact
Regulatory Mandates EU Taxonomy, TCFD, ISSB standards. Mandatory climate risk disclosures.
Investor Pressure ESG funds now exceed $35 trillion AUM. Banks risk capital flight if not ESG-compliant.
Customer Expectations 70% of Gen Z prefer sustainable brands. Green products drive customer acquisition.
Physical Risk Climate change impacts physical assets (collateral). Mortgage loan defaults in flood-prone areas.

2.2 Key Regulatory Frameworks

 
 
Framework Focus Requirement
TCFD (Task Force on Climate-related Financial Disclosures) Climate risk governance. Disclose emissions, scenario analysis.
EU Taxonomy Green economic activities. Define “environmentally sustainable” investments.
SFDR (Sustainable Finance Disclosure Regulation) Investment transparency. Classify funds as Article 6, 8, or 9.
ISSB IFRS S1/S2 Global sustainability reporting. Mandatory from 2025 in many jurisdictions.

SECTION 3: GREEN BANKING PRODUCTS

3.1 The Green Product Portfolio

 
 
Product Category Description Technology Enabler
Green Loans Lower rates for energy-efficient homes, EVs, solar panels. Automated eligibility checks (AI).
Sustainability-Linked Loans (SLLs) Interest rate tied to ESG performance metrics (e.g., carbon reduction). Real-time KPI monitoring via IoT.
Green Bonds Bonds funding renewable energy projects. Blockchain for transparency.
Carbon Trading & Offsets Facilitating carbon credit marketplaces. Smart contracts for settlements.
ESG-linked Deposits Deposits invested in green projects. Data-driven portfolio allocation.

3.2 Carbon Accounting 101

  • Scope 1: Direct emissions from owned sources (e.g., bank branches).

  • Scope 2: Indirect emissions from purchased energy.

  • Scope 3: All other indirect emissions (supply chain, customer operations, financed emissions – the largest for banks).

Financed Emissions account for ~95% of a bank’s carbon footprint – the emissions of companies and projects the bank finances.


SECTION 4: IMPLEMENTATION IN PYTHON – ESG DATA PIPELINE & SCORING

This section demonstrates how to aggregate ESG data and score a loan portfolio for carbon intensity.

python
# ===================================================================
# MODULE 10, LESSON 6: SUSTAINABLE BANKING & GREEN FINTECH
# ===================================================================

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime, timedelta
import warnings
warnings.filterwarnings('ignore')

print("="*70)
print("GREEN BANKING – ESG DATA PIPELINE & CARBON SCORING")
print("="*70)

# ----------------------------------------------------------------
# PART A: SIMULATING ESG DATA INGESTION (Multiple Sources)
# ----------------------------------------------------------------
print("\n" + "-"*60)
print("PART A: ESG Data Aggregation from Multiple Sources")
print("-"*60)

np.random.seed(42)

# Simulating corporate client ESG scores (Source 1: External ESG Rating Agency)
corporate_clients = pd.DataFrame({
    'client_id': [f'C{str(i).zfill(4)}' for i in range(1, 51)],
    'sector': np.random.choice(
        ['Energy', 'Manufacturing', 'Technology', 'Retail', 'Transportation', 'Real Estate', 'Financial Services'],
        50,
        p=[0.15, 0.2, 0.2, 0.15, 0.1, 0.1, 0.1]
    ),
    'revenue': np.random.uniform(10, 500, 50).round(2),  # $M
    'esg_score_third_party': np.random.randint(30, 95, 50),  # External agency rating (0-100)
    'carbon_intensity': np.random.uniform(0.1, 2.5, 50).round(2),  # tCO2e / $M revenue
    'green_revenue_pct': np.random.uniform(0, 80, 50).round(1)  # % of revenue from green products
})

# Simulating internal bank ESG data (Source 2: Internal Transactions & Operations)
corporate_clients['internal_carbon_estimate'] = corporate_clients['carbon_intensity'] * np.random.uniform(0.8, 1.2, 50)
corporate_clients['sustainability_risk'] = np.random.choice(['Low', 'Medium', 'High'], 50, p=[0.4, 0.4, 0.2])

print("Corporate Client ESG Dataset (Sample):")
print(corporate_clients.head(8).to_string(index=False))

# ----------------------------------------------------------------
# PART B: COMPOSITE ESG SCORE CALCULATION (Weighted Aggregation)
# ----------------------------------------------------------------
print("\n" + "-"*60)
print("PART B: Composite ESG Score & Green Classification")
print("-"*60)

# Weights for scoring
weights = {
    'esg_score_third_party': 0.35,
    'carbon_intensity': 0.25,  # Lower is better (inverted)
    'green_revenue_pct': 0.20,
    'sustainability_risk_mapping': 0.20
}

# Map sustainability risk to numeric
risk_mapping = {'Low': 90, 'Medium': 60, 'High': 30}
corporate_clients['risk_numeric'] = corporate_clients['sustainability_risk'].map(risk_mapping)

# Invert carbon intensity (higher carbon = lower score)
max_carbon = corporate_clients['carbon_intensity'].max()
corporate_clients['carbon_score'] = (1 - (corporate_clients['carbon_intensity'] / max_carbon)) * 100

# Calculate Composite ESG Score
corporate_clients['esg_composite_score'] = (
    weights['esg_score_third_party'] * corporate_clients['esg_score_third_party'] +
    weights['carbon_intensity'] * corporate_clients['carbon_score'] +
    weights['green_revenue_pct'] * corporate_clients['green_revenue_pct'] +
    weights['sustainability_risk_mapping'] * corporate_clients['risk_numeric']
).round(2)

# Classify clients into Green tiers
def classify_esg(score):
    if score >= 75:
        return 'Green (Low Carbon)'
    elif score >= 50:
        return 'Amber (Transitioning)'
    else:
        return 'Red (High Carbon)'

corporate_clients['esg_classification'] = corporate_clients['esg_composite_score'].apply(classify_esg)

print("\nComposite ESG Scores & Classification:")
print(corporate_clients[['client_id', 'sector', 'esg_composite_score', 'esg_classification']].head(10).to_string(index=False))

# ----------------------------------------------------------------
# PART C: PORTFOLIO CARBON FOOTPRINT DASHBOARD
# ----------------------------------------------------------------
print("\n" + "-"*60)
print("PART C: Portfolio Carbon Footprint Dashboard")
print("-"*60)

# Calculate portfolio-level metrics
portfolio_carbon = {
    'Total Clients': len(corporate_clients),
    'Average ESG Score': corporate_clients['esg_composite_score'].mean(),
    'Total Carbon Intensity (Portfolio)': corporate_clients['carbon_intensity'].sum(),
    'Average Carbon Intensity': corporate_clients['carbon_intensity'].mean(),
    'Green Clients (%)': (corporate_clients['esg_classification'] == 'Green (Low Carbon)').mean() * 100,
    'High Carbon Clients (%)': (corporate_clients['esg_classification'] == 'Red (High Carbon)').mean() * 100,
    'Total Green Revenue ($M)': corporate_clients['green_revenue_pct'].sum(),
}

print("\nPortfolio ESG Summary:")
for key, value in portfolio_carbon.items():
    if isinstance(value, float):
        print(f"  {key}: {value:.2f}")
    else:
        print(f"  {key}: {value}")

# ----------------------------------------------------------------
# PART D: VISUALIZATION – ESG SCORE DISTRIBUTION BY SECTOR
# ----------------------------------------------------------------
print("\n" + "-"*60)
print("PART D: ESG Performance by Sector (Visualization)")
print("-"*60)

# Create the visualization
fig, axes = plt.subplots(1, 2, figsize=(14, 6))

# Chart 1: ESG Score Distribution by Sector
sector_esg = corporate_clients.groupby('sector')['esg_composite_score'].agg(['mean', 'std']).reset_index()
sector_esg.columns = ['Sector', 'Mean_ESG', 'Std_ESG']
sector_esg = sector_esg.sort_values('Mean_ESG', ascending=False)

axes[0].barh(sector_esg['Sector'], sector_esg['Mean_ESG'], xerr=sector_esg['Std_ESG'], 
             color='green', alpha=0.7, edgecolor='black')
axes[0].axvline(x=75, color='red', linestyle='--', label='Green Threshold (75)')
axes[0].set_xlabel('Composite ESG Score')
axes[0].set_title('ESG Performance by Sector')
axes[0].legend()
axes[0].grid(True, alpha=0.3, axis='x')

# Chart 2: Client Classification Pie Chart
classification_counts = corporate_clients['esg_classification'].value_counts()
colors = {'Green (Low Carbon)': '#2ecc71', 'Amber (Transitioning)': '#f39c12', 'Red (High Carbon)': '#e74c3c'}
patches, texts, autotexts = axes[1].pie(
    classification_counts.values, 
    labels=classification_counts.index,
    autopct='%1.1f%%',
    colors=[colors.get(c, '#95a5a6') for c in classification_counts.index],
    startangle=90,
    explode=[0.05, 0, 0],
    shadow=True
)
axes[1].set_title('Portfolio ESG Classification')

plt.tight_layout()
plt.savefig('esg_portfolio_dashboard.png', dpi=300, bbox_inches='tight')
plt.show()
print("ESG Dashboard saved as 'esg_portfolio_dashboard.png'")

# ----------------------------------------------------------------
# PART E: GREEN LENDING DECISION ENGINE
# ----------------------------------------------------------------
print("\n" + "-"*60)
print("PART E: Green Lending Decision Engine")
print("-"*60)

class GreenLendingEngine:
    """
    Simulates an AI-driven decision engine for green loans.
    """
    def __init__(self, client_data):
        self.client_data = client_data
        
    def assess_loan_eligibility(self, client_id, loan_amount, loan_term_years):
        """Determines green loan eligibility and interest rate."""
        client = self.client_data[self.client_data['client_id'] == client_id]
        
        if client.empty:
            return {"error": "Client not found"}
        
        esg_score = client['esg_composite_score'].values[0]
        sector = client['sector'].values[0]
        carbon_intensity = client['carbon_intensity'].values[0]
        
        # Base interest rate
        base_rate = 8.5  # Standard bank rate
        
        # Green discount (lower rates for better ESG)
        if esg_score >= 75:
            discount = 2.0  # 2% discount
            decision = "Approved (Green Tier)"
        elif esg_score >= 50:
            discount = 0.75  # 0.75% discount
            decision = "Approved (Transitioning Tier)"
        else:
            discount = 0.0
            decision = "Conditional (Carbon Reduction Plan Required)"
            
        # Additional sector-specific adjustments
        if sector in ['Energy', 'Transportation'] and carbon_intensity > 1.5:
            decision += " - High carbon sector, additional scrutiny"
            discount = max(0, discount - 0.5)
            
        final_rate = base_rate - discount
        
        # Calculate repayment (simple amortization)
        monthly_rate = (final_rate / 100) / 12
        months = loan_term_years * 12
        if monthly_rate > 0:
            monthly_payment = loan_amount * (monthly_rate * (1 + monthly_rate) ** months) / ((1 + monthly_rate) ** months - 1)
        else:
            monthly_payment = loan_amount / months
            
        return {
            'client_id': client_id,
            'sector': sector,
            'esg_score': esg_score,
            'base_rate': base_rate,
            'discount': discount,
            'final_rate': round(final_rate, 2),
            'decision': decision,
            'loan_amount': loan_amount,
            'term_years': loan_term_years,
            'monthly_payment': round(monthly_payment, 2)
        }

# Instantiate the engine
lending_engine = GreenLendingEngine(corporate_clients)

# Test different clients
test_clients = ['C0001', 'C0020', 'C0045']
for client_id in test_clients:
    result = lending_engine.assess_loan_eligibility(client_id, loan_amount=1000000, loan_term_years=10)
    print(f"\nGreen Lending Assessment for {client_id}:")
    for key, value in result.items():
        if isinstance(value, float):
            print(f"  {key}: ${value:,.2f}" if 'payment' in key or 'amount' in key else f"  {key}: {value:.2f}")
        else:
            print(f"  {key}: {value}")

# ----------------------------------------------------------------
# SECTION 6: SUMMARY FOR THE DATA PRACTITIONER
# ----------------------------------------------------------------
print("\n" + "="*70)
print("LESSON 6 SUMMARY FOR THE DATA PRACTITIONER")
print("="*70)

print("""
1. Sustainable banking is driven by regulation (TCFD, EU Taxonomy), investor pressure, and customer demand.
2. Financed emissions (Scope 3) account for ~95% of a bank's carbon footprint – this is where data matters most.
3. Green Products: Green loans, Sustainability-Linked Loans (SLLs), Green bonds, Carbon trading.
4. Data Practitioner's role includes:
   - Aggregating ESG data from multiple sources (external ratings, internal metrics).
   - Calculating composite ESG scores and portfolio carbon footprints.
   - Building decision engines for green lending (as demonstrated).
   - Ensuring data quality for mandatory regulatory reporting.
5. Technology Enablers: AI for ESG scoring, IoT for real-time KPI monitoring, Blockchain for carbon credit traceability.
6. Action: Map your organization's data sources for ESG reporting and identify gaps in carbon intensity data.
""")

print("="*70)
print("END OF LESSON 6 – MODULE 10")
print("="*70)