Skip to main content

Risk-weighted assets attribution and capital optimization toolkit.

Project description

riskfolio_beta


riskfolio is a Python library for capital attribution, RWA (Risk-Weighted Assets) analysis, and profitability evaluation in financial risk management. It provides a modular and object-oriented framework to calculate, attribute, and visualize key risk metrics such as TCE (Tangible Common Equity) allocation, capital charge, return on capital, and RWA share.

The library is designed for quant developers, risk managers, and financial analysts who want a flexible and extensible way to model portfolio risk and performance attribution at various aggregation levels (e.g., desk, product, portfolio).

This library is still in beta version. Please read instructions carefully before using and check the details of each function when necessary.


📘 Overview: Risk Attribution for Modern Banking Portfolios

In the post-Basel III era, capital allocation is no longer a matter of simple portfolio optimization — it is a regulatory imperative. Banks are required to calculate and manage a series of risk-sensitive metrics such as Risk-Weighted Assets (RWA), Total Common Equity (TCE) allocation, and G-SIB (Global Systemically Important Bank) scores. These measures directly influence a bank’s minimum capital requirements, cost of equity, and even its systemic surcharge, shaping everything from product pricing to strategic asset mix.

This project provides a modular, Python-based library that demonstrates how these regulatory metrics can be computed, attributed, and stress-tested at a granular level (e.g., by desk, product, or counterparty). Built around synthetic fixed-income trading data, it illustrates the computational backbone behind modern regulatory reporting and internal capital allocation — serving as both a teaching tool and a foundation for production-scale systems.


⚖️ From Mean-Variance Allocation to Basel-Aligned Attribution

Traditional portfolio asset allocation techniques focus on optimizing risk-adjusted returns by balancing expected return, volatility, and correlation — often ignoring regulatory constraints. However, for banks subject to Basel III, capital is the scarce resource, and decisions must be evaluated through the lens of their regulatory cost. For example, a high-yield bond desk might offer attractive returns, but its elevated RWA and G-SIB contribution could erode net profitability once capital charges are considered.

This library bridges that gap. Instead of optimizing portfolios purely for Sharpe ratios or tracking error, it enables users to attribute capital consumption and regulatory costs across organizational dimensions. The result is a clear picture of which activities truly create economic value after accounting for regulatory drag, and how alternative risk-weight or business-mix scenarios would impact capital efficiency.


🚀 Features

  • Capital Charge Computation – Calculate capital charge and net income from allocated TCE and PnL.
  • Attribution Table Generation – Aggregate key metrics by desk, product, or other dimensions with automatically calculated performance ratios.
  • Scenario Analysis – Apply weight changes to products and instantly recompute RWA and profitability metrics.
  • Extensible Design – Built with modular components (core, reporting, validators, exceptions, etc.) to support future extensions.
  • Object-Oriented API – Easily integrate with larger analytics pipelines or use as a standalone analysis tool.

🧰 Core Functions & Usage Guide

This section provides a comprehensive overview of the core functions included in the library. Each function is designed to support portfolio risk attribution, Basel III capital calculations, and scenario analysis workflows. Below you’ll find the purpose, key parameters, return values, and sample usage examples for each major function.

To give a try on your own with these functions, you can download the mock data and code example.


1. compute_gsib_toy(df: pd.DataFrame) -> dict

Purpose:
Computes a simplified Global Systemically Important Bank (G-SIB) score based on portfolio data. The score is calculated from four dimensions defined by the Basel Committee: size, interconnectedness, complexity, and cross-jurisdictional activity.

Parameters:

Name Type Description
df pd.DataFrame Portfolio-level DataFrame containing columns such as EAD, desk, cp_rating, notional, product, maturity_days, and country.

Returns:
dict – A dictionary of scores for each G-SIB component and the total score.

Example:

from riskfolio.reporting import compute_gsib_toy

scores = compute_gsib_toy(df)
print(scores)

Output Example:

{
  "size_score": 68.52,
  "interconnectedness_score": 41.20,
  "complexity_score": 32.15,
  "cross_jurisdiction_score": 12.00,
  "G_SIB_total": 45.67
}

2. attribution_table(df: pd.DataFrame, dims=("desk",), metrics=None) -> pd.DataFrame

Purpose:
Generates a risk and return attribution table aggregated by one or more portfolio dimensions (e.g., desk, product, region). The table summarizes key financial metrics and performance indicators such as return on TCE and RWA-based returns.

Parameters:

Name Type Description
df pd.DataFrame Input portfolio data containing financial metrics.
dims tuple Columns to group by (default: ("desk",)).
metrics dict Optional mapping of metric names to aggregation methods. If None, defaults include notional, EAD, RWA, PnL, TCE_alloc, and Net_Income.

Returns:
pd.DataFrame – A summary attribution table with calculated metrics.

Example:

from riskfolio.reporting import attribution_table

summary = attribution_table(df, dims=("desk", "product"))
print(summary.head())

Output Example:

desk product notional EAD RWA PnL TCE_alloc Net_Income Return_on_TCE RWA_Return RWA_Share
Credit HY_Bond 21000000 1900000 890000 112000 450000 88000 0.1956 0.0988 0.42
Credit NonAgency_MBS 34000000 2700000 1100000 145000 550000 105000 0.1909 0.0954 0.52

3. apply_weight_scenario(df: pd.DataFrame, weight_changes: dict, level="product", col="notional") -> pd.DataFrame

Purpose:
Applies scenario adjustments to portfolio weights for sensitivity testing or stress scenario analysis. This function scales portfolio exposures (and related metrics like EAD) according to user-defined multipliers and recalculates RWA.

Parameters:

Name Type Description
df pd.DataFrame Original portfolio data.
weight_changes dict Mapping of portfolio categories (e.g., products) to scaling factors. Example: {"HY_Bond": 1.2, "NonAgency_MBS": 0.8}.
level str Column used for scaling (default: "product").
col str Exposure column to scale (default: "notional").

Returns:
pd.DataFrame – A modified portfolio DataFrame with updated exposure and RWA calculations.

Example:

from riskfolio.reporting import apply_weight_scenario

scenario = {
    "HY_Bond": 1.2,         # Increase HY bond exposure by 20%
    "NonAgency_MBS": 0.8    # Decrease MBS exposure by 20%
}

adjusted_df = apply_weight_scenario(df, weight_changes=scenario)

Output Preview:

product notional (after) EAD (after) RWA (after)
HY_Bond 25200000 2280000 920000
NonAgency_MBS 27200000 2160000 880000

Best Practice Tips:

  • Use apply_weight_scenario() before generating an attribution table if you want to evaluate the impact of portfolio adjustments.
  • Combine compute_gsib_toy() with attribution_table() to understand both systemic risk contribution and return efficiency under Basel III metrics.
  • Automate scenario sweeps by looping over different weight_changes dictionaries for sensitivity analysis.

📦 Installation

Use pip function in Python to install (easy and convenient):

pip install riskfolio-beta

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

riskfolio_beta-0.1.10.tar.gz (12.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

riskfolio_beta-0.1.10-py3-none-any.whl (11.7 kB view details)

Uploaded Python 3

File details

Details for the file riskfolio_beta-0.1.10.tar.gz.

File metadata

  • Download URL: riskfolio_beta-0.1.10.tar.gz
  • Upload date:
  • Size: 12.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.7

File hashes

Hashes for riskfolio_beta-0.1.10.tar.gz
Algorithm Hash digest
SHA256 319edb0d73bbf645ee0d40d0f095e36b760957a75c0b6ea05ace59d428445600
MD5 3c043470f624e2dd3ef31837d0ba63b2
BLAKE2b-256 ba305b029a26dc8d3ae27a5bb9a737dce20ffc66afab9b7f62caa607725f071a

See more details on using hashes here.

File details

Details for the file riskfolio_beta-0.1.10-py3-none-any.whl.

File metadata

File hashes

Hashes for riskfolio_beta-0.1.10-py3-none-any.whl
Algorithm Hash digest
SHA256 96a459b8890bc25dda727241d2d0bcdce06488645e61caf808c44afe304e4b91
MD5 03e11e3e2796b7b9bcaf20a8495f185a
BLAKE2b-256 cd140600f2b1237249288175b8af668324976ce7f2abb39f4990167b7fc3b31a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page