Risk-weighted assets attribution and capital optimization toolkit.
Project description
riskfolio_beta
- 📘 Overview: Risk Attribution for Modern Banking Portfolios
- ⚖️ From Mean-Variance Allocation to Basel-Aligned Attribution
- 🚀 Features
- 🧰 Core Functions & Usage Guide
- 📦 Installation
riskfolio_beta 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()withattribution_table()to understand both systemic risk contribution and return efficiency under Basel III metrics. - Automate scenario sweeps by looping over different
weight_changesdictionaries for sensitivity analysis.
📦 Installation
Use pip function in Python to install (easy and convenient):
pip install riskfolio-beta
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file riskfolio_beta-0.1.12.tar.gz.
File metadata
- Download URL: riskfolio_beta-0.1.12.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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
2d5e6b33528722bd2d722483676f8d81d687a6d7bad58df97840354d5893258c
|
|
| MD5 |
63c3c4eec92ce9eaf4c96397a9b1287b
|
|
| BLAKE2b-256 |
3e0c4589945c025b28712e1be1c2315313b20c0d169940ea5f5d2f2c6c763c68
|
File details
Details for the file riskfolio_beta-0.1.12-py3-none-any.whl.
File metadata
- Download URL: riskfolio_beta-0.1.12-py3-none-any.whl
- Upload date:
- Size: 11.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
9cdb84efa531c4ceaf8bba72c250122808ce91cb4b141781876a45d323ee6092
|
|
| MD5 |
399e4f3a2b634046b34395ea0d507fd7
|
|
| BLAKE2b-256 |
ee135180d3644a742da4df4153974a21794fee9be798ac0ad19c89f71403ccfa
|