The user wants a Python application that serves as a "supply-chain due diligence finance overlay."
This system needs to comply with specific regulations: German (LkSG), French (Loi de Vigilance), and EU-wide (CSDDD/CSRD) sustainability directives.
It must include KPI (Key Performance Indicator) tracking.
1. Understanding the Requirements:
- Supply Chain Due Diligence (SCDD): This involves tracking suppliers, assessing risks (environmental, social, governance), and monitoring compliance.
- Regulations:
- German LkSG (Lieferkettensorgfaltspflichtengengesetz): Focuses on human rights and environmental due diligence.
- French Loi de Vigilance: Similar to LkSG but covers a broader range of risks and requires a "Vigilance Plan."
- EU CSDDD (Corporate Sustainability Due Diligence Directive) & CSRD (Corporate Sustainability Reporting Directive): Broader scope, integration into corporate strategy, and specific reporting standards (ESRS).
- Finance Overlay: This implies connecting the supply chain data to financial impacts. How does non-compliance or risk affect costs, revenue, or capital? It suggests a dashboard or analysis tool for CFOs/investors.
- KPI Tracking: We need metrics. Examples: Carbon emissions (Scope 3), labor violation incidents, audit completion rates, financial exposure at risk.
- Output: A Python-based solution (likely a dashboard using Streamlit or Dash, or a class structure for backend processing). Given the complexity, a Streamlit dashboard is the most visual and interactive way to demonstrate this.
2. Conceptual Architecture:
- Data Model:
- Suppliers (ID, Name, Country, Tier, Industry, Risk Score).
- Compliance Data (Audit Status, Violation Count, Certifications).
- Financial Data (Spend Volume, Contract Value).
- ESG Data (CO2e emissions, Water usage).
- Logic/Calculation Engine:
- Risk Scoring: Combine country risk + industry risk + past violations.
- Regulatory Mapping: Tag suppliers based on which regulation applies (e.g., threshold checks).
- Financial Impact: Calculate "Value at Risk" (VaR) based on supply chain disruptions or fines.
- Visualization (Dashboard):
- Overview of Compliance (Red/Amber/Green).
- Map view of suppliers.
- KPI charts.
- Financial breakdown.
3. Developing the Python Code (Step-by-Step):
- Libraries:
pandas for data manipulation, numpy for calcs, streamlit for UI, plotly for charts.
- Synthetic Data Generation: Since I don't have access to real corporate data, I need to create a robust mock dataset. This makes the code runnable immediately.
- Create a DataFrame of ~20-50 suppliers.
- Assign regions (Germany, France, China, India, etc.).
- Assign random values for CO2, Child Labor Risk, Wage violations, etc.
- Compliance Logic:
- LkSG: Check for human rights violations.
- CSRD: Check for Scope 3 emissions (Science Based Targets).
- Financials: Calculate Total Spend vs. High-Risk Spend.
- The "Overlay" Aspect: This is the crucial part. It's not just an ESG report; it's a finance overlay.
- Calculation: Compliance Cost = (Remediation efforts + Potential Fines).
- Calculation: Stranded Asset Risk = Suppliers failing 2030 climate goals.
- UI Layout:
- Sidebar: Filters (Region, Regulation).
- Main: Top-line KPI cards.
- Charts: Risk Heatmap, Spend vs. Emissions scatter plot, Compliance Gaps.
4. Refining the Logic for Specific Regulations:
- LkSG (Germany): Focus on "Duty of Care." KPI: % of suppliers audited.
- Loi de Vigilance (France): Focus on "Vigilance Plan." KPI: Severity of impact.
- EU CSRD: Focus on "Double Materiality." KPI: Scope 3 GHG intensity per € revenue.
5. Drafting the Code Structure:
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
# 1. Data Generation
# 2. Logic Class (ComplianceEngine)
# 3. Dashboard Layout
6. Adding Detail to the Financial Overlay:
How do we quantify this?
- Risk Exposure: Total contract value with suppliers flagged "Red".
- Carbon Price: Estimating future cost based on current emissions * projected carbon tax (e.g., €80/ton).
7. Reviewing the Prompt's specific request:
"German, French, and EU directives."
- German: LkSG (Supply Chain Due Diligence Act).
- French: Loi de Vigilance (Duty of Vigilance Law).
- EU: CSDDD (Directive) and CSRD (Reporting).
I will structure the dashboard to allow the user to filter by these specific mandates.
8. Writing the actual code (Mental Draft & Refinement):
- Setup: Standard Streamlit boilerplate.
- Data: Need specific columns:
country, tier, spend, co2_emissions, labor_risk_score, env_risk_score.
- Calculations:
lksg_compliance = boolean based on risk scores.
financial_risk_exposure = sum of spend where compliance is false.
- Visuals:
- Gauge charts for KPIs.
- Scatter plot for "Cost vs. Risk" (High spend, high risk = top priority).
9. Final Polish:
Ensure the code is self-contained (generates its own data) and includes comments explaining how the logic maps to the regulations.
Self-Correction during drafting: I shouldn't just list the laws. I need to show how the tool tracks them.
- Feature: A "Compliance Gap Analysis" table.
- Feature: A "Financial Impact" summary.
Let's generate the Python script.
10. Final Output Structure:
- Executive Summary: Explanation of the solution.
- Python Code: A complete, runnable Streamlit application.
- Key Features Walkthrough: Explaining the dashboard sections.
- Regulatory Mapping: Brief text explaining the logic behind the KPIs.
(Self-Correction): The user asked for a "Finance Overlay." I need to make sure financial metrics are prominent.
I will add a "Shadow Carbon Price" calculation and a "Fine Exposure" estimate based on EU turnover (a common penalty metric).
Let's proceed with generating the code.
This solution provides a comprehensive Python application using Streamlit for the frontend and Pandas/Plotly for backend logic and visualization.
This tool acts as a Finance Overlay, meaning it connects operational supply chain data with financial exposure to assess compliance with the German LkSG, French Loi de Vigilance, and the EU CSDDD/CSRD.
Prerequisites
To run this, you need Python installed. Install the necessary libraries:
pip install streamlit pandas plotly numpy
The Solution: supply_chain_due_diligence.py
Save the following code into a file named supply_chain_due_diligence.py.
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime, timedelta
# ==========================================
# 1. CONFIGURATION & REGULATORY LOGIC
# ==========================================
REGULATIONS = {
"German LkSG (Supply Chain Act)": {
"focus": ["Human Rights", "Environmental"],
"threshold_employee": 3000, # (2023), drops to 1000 in 2024
"compliance_mandatory": True
},
"French Loi de Vigilance": {
"focus": ["Human Rights", "Environmental", "Health & Safety"],
"threshold_employee": 5000, # (France HQ)
"compliance_mandatory": True
},
"EU CSDDD (Due Diligence Directive)": {
"focus": ["Human Rights", "Environmental", "Climate Transition"],
"threshold_employee": 1000, # Proposed threshold
"threshold_turnover_mio": 450, # Proposed threshold
"compliance_mandatory": True
}
}
# ==========================================
# 2. DATA GENERATION (SIMULATION)
# ==========================================
@st.cache_data
def generate_supply_chain_data():
"""
Generates synthetic data representing a supplier network with
risk scores, financial exposure, and ESG metrics.
"""
np.random.seed(42)
n_suppliers = 50
suppliers = [f"SUP-{i:03d}" for i in range(1, n_suppliers + 1)]
countries = np.random.choice(['Germany', 'France', 'China', 'India', 'Vietnam', 'USA', 'Brazil'], n_suppliers)
industries = np.random.choice(['Electronics', 'Textiles', 'Raw Materials', 'Logistics', 'Assembly'], n_suppliers)
# Generate Data
data = pd.DataFrame({
'Supplier_ID': suppliers,
'Country': countries,
'Industry': industries,
'Tier': np.random.choice([1, 2, 3], n_suppliers, p=[0.3, 0.5, 0.2]),
'Annual_Spend_EUR': np.random.randint(500000, 50000000, n_suppliers),
# Risk Scores (0-100, where 100 is high risk)
'Labor_Risk_Score': np.random.randint(0, 100, n_suppliers),
'Environmental_Score': np.random.randint(0, 100, n_suppliers),
'Corruption_Risk_Score': np.random.randint(0, 100, n_suppliers),
# Compliance Documentation Status
'Code_of_Conduct_Signed': np.random.choice([True, False], n_suppliers, p=[0.8, 0.2]),
'Audit_Valid': np.random.choice([True, False], n_suppliers, p=[0.7, 0.3]),
# ESG Metrics for CSRD/Finance Overlay
'Scope_3_Emissions_tCO2e': np.random.uniform(100, 10000, n_suppliers),
'Water_Usage_m3': np.random.uniform(500, 50000, n_suppliers),
})
# Add a "Critical Incident" flag for some suppliers
data['Critical_Incident'] = np.random.choice([None, 'Strike', 'Spill', 'Child Labor Allegation', 'Wage Theft'], n_suppliers, p=[0.85, 0.05, 0.03, 0.04, 0.03])
return data
# ==========================================
# 3. FINANCE OVERLAY LOGIC
# ==========================================
def calculate_financial_risk_exposure(df):
"""
Calculates Value at Risk (VaR) based on regulatory non-compliance
and operational risks.
"""
# Regulatory Fines Estimate (Simplified)
# e.g., LkSG can be up to 2% of avg annual turnover, Loi de Vigilance up to 10M EUR (civil liability much higher)
# Heuristic: If a supplier has High Risk ( > 75) AND High Spend, the Financial Exposure is high.
df['Composite_Risk'] = (df['Labor_Risk_Score'] * 0.4 +
df['Environmental_Score'] * 0.3 +
df['Corruption_Risk_Score'] * 0.3)
# Normalize Composite Risk to 0-1
df['Composite_Risk_Norm'] = df['Composite_Risk'] / 100
# Financial Impact Score: Spend * Risk
df['Financial_Exposure_EUR'] = df['Annual_Spend_EUR'] * df['Composite_Risk_Norm']
# Estimate Potential Fines (High risk scenarios)
# Assume 0.5% of spend might be at risk of immediate disruption or fine
df['Potential_Fine_Risk_EUR'] = df['Annual_Spend_EUR'].where(
(df['Labor_Risk_Score'] > 80) | (df['Environmental_Score'] > 80), 0
) * 0.005 # 0.5% penalty estimation
return df
# ==========================================
# 4. DASHBOARD UI
# ==========================================
def main():
st.set_page_config(layout="wide", page_title="SCDD Finance Overlay")
st.title("🌍 Supply Chain Due Diligence & Finance Overlay")
st.markdown(f"**Compliance Dashboard:** German LkSG | French Loi de Vigilance | EU CSDDD/CSRD")
st.markdown(f"Last Updated: {datetime.now().strftime('%Y-%m-%d')}")
# Load Data
df = generate_supply_chain_data()
df = calculate_financial_risk_exposure(df)
# --- SIDEBAR FILTERS ---
st.sidebar.header("Filters")
regulation_filter = st.sidebar.multiselect(
"Filter by Regulatory Focus",
["German LkSG", "French Loi de Vigilance", "EU CSDDD"],
default=["German LkSG", "French Loi de Vigilance", "EU CSDDD"]
)
risk_threshold = st.sidebar.slider("Min Risk Score to Display", 0, 100, 50)
tier_filter = st.sidebar.multiselect("Supply Chain Tier", [1, 2, 3], default=[1, 2, 3])
# Apply Filters
df_view = df[
(df['Tier'].isin(tier_filter)) &
(df['Composite_Risk'] >= risk_threshold)
].copy()
# --- TOP LEVEL KPIs ---
st.markdown("### 📊 Executive Summary")
total_spend = df['Annual_Spend_EUR'].sum()
total_exposure = df_view['Financial_Exposure_EUR'].sum()
high_risk_suppliers = len(df[df['Composite_Risk'] > 75])
open_incidents = len(df[df['Critical_Incident'].notna()])
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric(label="Total Spend Tracked", value=f"€{total_spend/1e6:.1f}M")
with col2:
st.metric(label="Financial Risk Exposure", value=f"€{total_exposure/1e6:.1f}M", delta_color="inverse")
with col3:
st.metric(label="High Risk Suppliers", value=high_risk_suppliers, delta=f"{high_risk_suppliers} Require Review")
with col4:
st.metric(label="Active Incidents", value=open_incidents, delta_color="inverse")
st.markdown("---")
# --- MAIN VISUALIZATIONS ---
# 1. RISK HEATMAP (SPEND VS RISK)
st.markdown("#### 💸 Financial Exposure Overlay (Spend vs. Risk)")
st.info("Suppliers in the top-right quadrant (High Spend, High Risk) represent the greatest financial liability under EU directives.")
fig_scatter = px.scatter(
df_view,
x="Composite_Risk",
y="Annual_Spend_EUR",
size="Scope_3_Emissions_tCO2e",
color="Critical_Incident",
hover_name="Supplier_ID",
title="Supplier Risk vs. Spend (Bubble Size = CO2 Emissions)",
color_discrete_map={None: "grey", "Strike": "orange", "Spill": "red", "Child Labor Allegation": "darkred", "Wage Theft": "yellow"},
labels={"Composite_Risk": "Composite ESG Risk Score (0-100)"}
)
fig_scatter.add_vline(x=75, line_dash="dash", line_color="red", annotation_text="High Risk Threshold")
st.plotly_chart(fig_scatter, use_container_width=True)
# 2. GEOGRAPHICAL RISK MAP
st.markdown("#### 🗺️ Geopolitical & ESG Risk Distribution")
country_stats = df.groupby('Country').agg({
'Annual_Spend_EUR': 'sum',
'Composite_Risk': 'mean',
'Supplier_ID': 'count'
}).reset_index().rename(columns={'Supplier_ID': 'Supplier_Count'})
fig_map = px.choropleth(
country_stats,
locations="Country",
locationmode="country names",
color="Composite_Risk",
hover_data=['Annual_Spend_EUR', 'Supplier_Count'],
color_continuous_scale=px.colors.sequential.OrRd,
title="Average Supply Chain Risk by Country"
)
st.plotly_chart(fig_map, use_container_width=True)
# 3. REGULATORY COMPLIANCE DRILL-DOWN
st.markdown("#### 📑 Regulatory Compliance KPIs")
tab1, tab2, tab3 = st.tabs(["German LkSG", "French Loi de Vigilance", "EU CSDDD / ESG"])
with tab1:
st.markdown("**Focus: Human Rights & Environmental Due Diligence**")
# LkSG KPI: % of Suppliers audited
audited_pct = (df[df['Tier'] == 1]['Audit_Valid'].mean()) * 100
coc_pct = (df['Code_of_Conduct_Signed'].mean()) * 100
c1, c2 = st.columns(2)
c1.metric("Tier 1 Suppliers Audited (Valid)", f"{audited_pct:.1f}%")
c2.metric("Code of Conduct Signed", f"{coc_pct:.1f}%")
# List of non-compliant
non_compliant = df[(df['Audit_Valid'] == False) | (df['Code_of_Conduct_Signed'] == False)]
st.warning(f"Found {len(non_compliant)} suppliers with missing LkSG documentation.")
st.dataframe(non_compliant[['Supplier_ID', 'Country', 'Annual_Spend_EUR', 'Audit_Valid', 'Code_of_Conduct_Signed']])
with tab2:
st.markdown("**Focus: Vigilance Plan & Severe Impact**")
# Filter for 'Severe' impacts (Incidents)
incidents = df[df['Critical_Incident'].notna()]
fig_bar = px.bar(
incidents.groupby('Country').size().reset_index(name='Count'),
x='Country', y='Count', color='Country',
title="Locations of Reported Vigilance Incidents"
)
st.plotly_chart(fig_bar, use_container_width=True)
with tab3:
st.markdown("**Focus: Climate Transition (Scope 3) & Finance**")
# Carbon Intensity vs Spend
fig_treemap = px.treemap(
df,
path=[px.Constant("All Suppliers"), 'Industry', 'Supplier_ID'],
values='Annual_Spend_EUR',
color='Scope_3_Emissions_tCO2e',
color_continuous_scale='RdBu_r',
title="Supply Chain Spend weighted by CO2 Emissions (Scope 3)"
)
st.plotly_chart(fig_treemap, use_container_width=True)
# --- DETAILED DATA TABLE ---
st.markdown("### 📋 Supplier Risk Ledger")
st.dataframe(
df_view.sort_values('Financial_Exposure_EUR', ascending=False)[
['Supplier_ID', 'Country', 'Tier', 'Industry', 'Annual_Spend_EUR', 'Composite_Risk', 'Financial_Exposure_EUR', 'Critical_Incident']
],
height=400
)
if __name__ == "__main__":
main()
How to Run
- Save the code above as
supply_chain_due_diligence.py.
- Open your terminal or command prompt.
- Run the command:
streamlit run supply_chain_due_diligence.py.
Key Features of This Overlay
1. The "Finance Overlay" Concept
Unlike a standard ESG dashboard, this tool calculates a Financial Exposure Estimate.
- Formula:
Annual Spend * Composite Risk Score.
- Logic: It prioritizes suppliers who may not have the highest absolute risk score, but whose failure or non-compliance would cost the company the most money (e.g., a Tier 1 electronics supplier with medium risk vs. a Tier 3 stationery supplier with high risk).
2. Regulatory Mapping
- LkSG (Germany): The dashboard tracks "Code of Conduct" and "Audit Valid" status, which are core requirements of the German Act. It specifically filters for Tier 1 suppliers where the direct responsibility lies.
- Loi de Vigilance (France): This requires a "Vigilance Plan." The dashboard maps Critical Incidents (Strikes, Spills, Allegations) to show where the plan is failing or needs intervention.
- EU CSDDD/CSRD: This focuses heavily on climate transition. The Scope 3 Emissions bubble chart and treemap allow finance teams to see where carbon hotspots exist within their spending portfolio.
3. KPI Tracking
- Audited Suppliers (%): Tracks due diligence coverage.
- Financial Exposure (€): Quantifies the liability of the supply chain.
- CO2 Intensity: Tracks environmental impact per spend/industry.
4. Actionable Insights
- The Scatter Plot immediately identifies the "Danger Zone" (Top Right: High Spend + High Risk).
- The Data Table allows for sorting by
Financial_Exposure_EUR so the compliance officer knows who to contact first.