Financial Risk Analysis Project with Python

Data Analytics project 20

Financial Risk Analysis Project with Python

Build a complete financial risk analysis portfolio project with documented metrics, reproducible Python code, validation checks, and responsible interpretation.

Explore Data Analytics training in VizagView all project ideas

Business question

What are portfolio expected loss, a simple stressed loss, and exposure concentration by sector?

Dataset and grain

One thousand five hundred synthetic credit exposures with sector, rating, exposure at default, probability of default, and loss given default.

Requirements

Python 3.10 or later with numpy and pandas installed.

Method and validation checks

Calculate expected loss as EAD times PD times LGD, apply transparent stressed PD and LGD assumptions with caps, aggregate by sector, and calculate exposure shares.

  • PD and LGD remain between zero and one
  • Sector EAD shares sum to one
  • Stressed assumptions are disclosed and capped
  • Expected loss is not confused with unexpected loss or capital

Complete Python code

Save the code as da_financial_risk_analysis.py. Review the stated model and field assumptions before using another dataset.

"""Calculate synthetic credit expected loss and concentration indicators."""

from __future__ import annotations

import numpy as np
import pandas as pd


def make_demo_exposures(n: int = 1_500, seed: int = 42) -> pd.DataFrame:
    rng = np.random.default_rng(seed)
    rating = rng.choice(["A", "B", "C", "D"], n, p=[0.28, 0.36, 0.25, 0.11])
    pd_map = {"A": 0.004, "B": 0.015, "C": 0.055, "D": 0.16}
    probability_default = pd.Series(rating).map(pd_map).to_numpy()
    return pd.DataFrame({"exposure_id": range(1, n + 1), "sector": rng.choice(["Retail", "Manufacturing", "Services", "Technology"], n),
                         "rating": rating, "ead": rng.lognormal(12.0, 0.9, n).round(2),
                         "pd": probability_default, "lgd": rng.uniform(0.25, 0.7, n)})


def analyse_risk(data: pd.DataFrame) -> tuple[dict[str, float], pd.DataFrame]:
    risk = data.copy()
    risk["expected_loss"] = risk["ead"] * risk["pd"] * risk["lgd"]
    risk["stressed_expected_loss"] = risk["ead"] * np.minimum(risk["pd"] * 1.5, 1) * np.minimum(risk["lgd"] + 0.1, 1)
    total_ead = risk["ead"].sum()
    sectors = risk.groupby("sector", as_index=False).agg(ead=("ead", "sum"), expected_loss=("expected_loss", "sum"), stressed_expected_loss=("stressed_expected_loss", "sum"))
    sectors["ead_share"] = sectors["ead"] / total_ead
    kpis = {"total_ead": float(total_ead), "expected_loss": float(risk["expected_loss"].sum()), "stressed_expected_loss": float(risk["stressed_expected_loss"].sum()), "largest_sector_share": float(sectors["ead_share"].max())}
    return kpis, sectors.sort_values("ead", ascending=False)


def main() -> None:
    kpis, sectors = analyse_risk(make_demo_exposures())
    print({k: round(v, 3) for k, v in kpis.items()})
    print(sectors.round(3).to_string(index=False))
    print("Synthetic educational assumptions; not a validated regulatory, lending, or investment model.")


if __name__ == "__main__":
    main()

Build and run the project

Run python da_financial_risk_analysis.py to calculate synthetic expected loss, stress loss, and sector concentration.

  1. Confirm the source grain and field definitions.
  2. Reconcile record counts and additive totals.
  3. Validate rate denominators and date filters.
  4. Review outliers and missing values.
  5. Read the interpretation limits before sharing conclusions.

Expected analytical output

Portfolio EAD, expected loss, stressed expected loss, largest-sector share, and a sector breakdown.

Interpretation and responsible-use limits

Synthetic education only. This is not a validated regulatory, lending, pricing, capital, accounting, stress-testing, or investment model. Real risk work requires governance, calibration, backtesting, and expert review.

Ways to extend the project

Add maturity, collateral, default correlation, vintage analysis, calibration curves, scenario design, uncertainty, backtesting, and governance documentation.

Continue learning Data Analytics

Try the next project, return to the Softenant project library, or explore the Data Analytics course in Vizag for guided SQL, Excel, Power BI, Python, dashboard, and portfolio practice.