This calculator helps determine the risk-weighted assets (RWA) for various asset classes under the Basel II framework, influencing a bank's capital adequacy ratio.
Sovereign
Corporate
Retail
Residential Mortgage
Commercial Mortgage
Equity
Other
Select the type of asset.
The total value of the exposure.
AAA to AA-
A+ to A-
BBB+ to BBB-
BB+ to BB-
B+ to B-
CCC+ and below
Unrated
The credit rating assigned by a recognized credit rating agency.
Calculation Results
—
—
—
—
Formula: RWA = Exposure Value * Risk Weight (%)
Risk Weight vs. Capital Requirement
Illustrative comparison of Risk Weight and potential Capital Requirement based on a fixed exposure value.
What is Basel II Risk Weight Calculation?
The Basel II risk weight calculation is a fundamental component of the Basel Accords, designed to ensure that banks hold sufficient capital against the risks they undertake. It's a standardized approach that assigns a specific risk weight to different types of assets held by a bank. This risk weight is then multiplied by the exposure value of the asset to determine its Risk-Weighted Assets (RWA). The total RWA across all assets forms the denominator in the capital adequacy ratio (CAR), a key metric for regulatory oversight and financial stability. Essentially, assets deemed riskier attract higher risk weights, thus requiring banks to hold more capital against them.
This calculation is primarily used by banks and other financial institutions that are subject to Basel II (or subsequent Basel III) regulations. It's crucial for internal risk management, strategic decision-making regarding asset allocation, and meeting regulatory compliance requirements. A common misconception is that risk weights are static; in reality, they can vary significantly based on the asset class, the creditworthiness of the counterparty, and specific regulatory treatments.
Basel II Risk Weight Calculation Formula and Mathematical Explanation
The core of the Basel II risk weight calculation is straightforward:
Risk-Weighted Assets (RWA) = Exposure Value × Risk Weight (%)
This formula translates the credit risk associated with an asset into a standardized measure that can be compared across different asset types and institutions. The complexity lies in determining the appropriate Risk Weight (RW) for each asset class.
Variable Explanations
Let's break down the components:
Exposure Value (EV): This is the amount of money a bank stands to lose if a borrower defaults. It represents the total value of the asset or loan on the bank's balance sheet.
Risk Weight (RW): This is a percentage assigned by regulators to an asset class, reflecting its perceived credit risk. Higher risk weights mean higher potential for default or loss.
Risk-Weighted Assets (RWA): The final calculated value, representing the riskiness of an asset in terms of capital requirements.
Variables Table
Key Variables in Basel II Risk Weight Calculation
Variable
Meaning
Unit
Typical Range
Exposure Value (EV)
The total value of the asset or loan.
Currency (e.g., USD, EUR)
≥ 0
Risk Weight (RW)
Percentage reflecting the credit risk of the asset.
Percentage (%)
0% to 150% (or higher for certain categories like retail, equity, operational risk)
Risk-Weighted Assets (RWA)
The exposure value adjusted for risk.
Currency (e.g., USD, EUR)
≥ 0
Capital Adequacy Ratio (CAR)
(Tier 1 Capital + Tier 2 Capital) / RWA
Percentage (%)
Minimum regulatory requirement (e.g., 8%)
Determining Risk Weights
Basel II provides specific methodologies for assigning risk weights, which differ based on the approach used (Standardised Approach or Internal Ratings-Based approach). For the Standardised Approach, risk weights are generally determined by:
Asset Class: Different asset classes (e.g., sovereign debt, corporate loans, retail loans, mortgages) have pre-defined risk weights.
Credit Quality: For rated assets, the credit rating assigned by recognized credit rating agencies (CRAs) dictates the risk weight. Higher ratings (e.g., AAA) get lower risk weights, while lower ratings (e.g., B-) get higher risk weights.
Specific Features: Certain features like maturity, collateral, guarantees, or regulatory definitions (e.g., for residential mortgages) can adjust the risk weight.
For example, under the Standardised Approach:
Sovereign debt rated AAA to AA- might have a 0% risk weight.
Corporate exposures might have a standard 100% risk weight, adjusted based on rating.
Retail exposures typically have a 75% risk weight, provided they meet specific criteria.
Residential mortgages meeting certain LTV (Loan-to-Value) criteria might have a 35% or 50% risk weight.
Equity exposures can have significantly higher risk weights, often 250% or more, depending on the type.
The basel ii risk weight calculation is thus a critical step in assessing a bank's solvency and its ability to absorb unexpected losses.
Practical Examples (Real-World Use Cases)
Example 1: Sovereign Debt Exposure
A large international bank holds €50 million in bonds issued by a country with a credit rating of AA-.
Asset Class: Sovereign
Exposure Value (EV): €50,000,000
Credit Rating: AA-
According to Basel II Standardised Approach rules, sovereign debt rated AAA to AA- typically carries a 0% risk weight.
Interpretation: This exposure is considered very low risk by regulators, requiring no specific capital allocation against it under Basel II's credit risk framework. This encourages holding high-quality sovereign debt.
Example 2: Corporate Loan Exposure
A regional bank has provided a loan of $10 million to a mid-sized corporation rated BBB+.
Asset Class: Corporate
Exposure Value (EV): $10,000,000
Credit Rating: BBB+
Under Basel II Standardised Approach, corporate exposures rated BBB+ typically attract a 100% risk weight.
Interpretation: This loan is assigned RWA equal to its exposure value, indicating a standard level of credit risk. The bank must hold capital equivalent to a percentage of this $10 million RWA, based on its overall Capital Adequacy Ratio requirement.
Example 3: Residential Mortgage Exposure
A bank has a mortgage portfolio with a total exposure value of £20 million. These mortgages meet the criteria for a 50% risk weight (e.g., LTV ratio below 80%).
Interpretation: Residential mortgages, being generally considered less risky than unsecured corporate loans, receive a lower risk weight. This results in lower RWA (£10 million) compared to the exposure value, reducing the capital burden for the bank.
How to Use This Basel II Risk Weight Calculator
Our Basel II Risk Weight Calculator is designed for simplicity and accuracy. Follow these steps:
Select Asset Class: Choose the type of asset from the dropdown menu (e.g., Sovereign, Corporate, Retail, Equity).
Input Exposure Value: Enter the total monetary value of the asset or loan in the provided field. Ensure you use the correct currency value.
Provide Specifics: Depending on the asset class, you may need to select a credit rating (for sovereigns and corporates) or other relevant criteria. The calculator will dynamically adjust the input fields based on your selection.
Calculate: Click the "Calculate" button.
Reading the Results:
Risk-Weighted Assets (RWA): This is the primary result. It represents the exposure value adjusted for credit risk, forming the basis for capital requirements.
Risk Weight (%): Shows the percentage assigned to your asset based on its class and characteristics.
Exposure Value: Confirms the input value you provided.
Capital Requirement (Illustrative): This is an estimated capital amount required, calculated as RWA multiplied by a standard minimum capital ratio (e.g., 8%). Note: This is illustrative and actual regulatory capital requirements may vary.
Decision-Making Guidance:
Use the results to understand the risk profile of different assets. Higher RWA implies a greater capital charge. Banks can use this information to:
Optimize their balance sheet by favoring assets with lower RWA for a given return.
Assess the impact of credit rating changes on their capital requirements.
Ensure compliance with regulatory capital ratios.
Compare the risk-return profile of different investment or lending opportunities.
The chart provides a visual representation, helping to quickly grasp the relationship between risk weights and potential capital needs.
Key Factors That Affect Basel II Risk Weight Results
Several factors significantly influence the outcome of a basel ii risk weight calculation:
Asset Class Definition: The fundamental classification of an asset (e.g., corporate vs. retail vs. sovereign) dictates the baseline risk weight range. Regulatory definitions are precise and must be adhered to.
Credit Rating: For rated exposures (sovereigns, corporates, banks), the assigned credit rating is a primary driver. A downgrade can substantially increase the risk weight and thus the RWA. This is a direct reflection of the counterparty's perceived ability to repay.
Loan-to-Value (LTV) Ratio: Particularly relevant for mortgages, a lower LTV (meaning the loan amount is a smaller percentage of the property's value) generally results in a lower risk weight, reflecting reduced loss given default.
Maturity: While less prominent in the basic Standardised Approach for some asset classes, longer-term exposures can sometimes attract higher risk weights due to increased uncertainty over time.
Regulatory Treatment & Specific Rules: Basel II includes specific rules for certain exposures, such as exposures to other banks, SMEs, or exposures in default. These can lead to significantly different risk weights than standard categories.
Collateral and Guarantees: The presence of eligible collateral or guarantees from highly-rated entities can sometimes reduce the effective exposure value or allow for a lower risk weight, mitigating potential losses.
Unrated Exposures: For assets lacking a credit rating, Basel II often assigns a higher, more conservative risk weight (e.g., 100% for unrated corporates) or requires specific internal assessment methodologies.
Frequently Asked Questions (FAQ)
Q1: What is the difference between Basel II and Basel III regarding risk weights?
Basel III built upon Basel II, introducing stricter capital requirements and refining risk-weighted asset calculations, particularly for market and operational risks. It also introduced capital conservation buffers and leverage ratios. While the core concept of risk weights remains, Basel III often leads to higher RWA for similar exposures.
Q2: Can risk weights be negative?
No, risk weights are always non-negative percentages (0% or higher). They represent the degree of risk, and a negative risk would imply a benefit, which is not how credit risk is measured.
Q3: How often are risk weights updated?
The regulatory framework for risk weights is set by Basel Committee guidelines and implemented by national regulators. Changes are infrequent but can occur due to updates in the Basel Accords or specific market conditions. Individual asset ratings, however, can change much more frequently.
Q4: What is the role of credit rating agencies in Basel II?
For the Standardised Approach, credit rating agencies (like S&P, Moody's, Fitch) play a crucial role. Their ratings are mapped directly to specific risk weights for eligible exposures like corporate debt and sovereign debt.
Q5: What happens if an asset is unrated?
Unrated assets typically receive a higher, more conservative risk weight. For instance, unrated corporate exposures often default to a 100% risk weight under the Standardised Approach, reflecting a lack of external credit assessment.
Q6: Does Basel II consider operational risk and market risk in its risk weight calculation?
The basic Basel II framework primarily focuses on credit risk for the Standardised Approach. Separate methodologies exist within Basel II to calculate capital requirements for operational risk and market risk, which are added to the credit risk RWA to determine total RWA.
Q7: How does the Internal Ratings-Based (IRB) approach differ from the Standardised Approach?
The IRB approach allows sophisticated banks to use their own internal models to estimate risk parameters (like Probability of Default, Loss Given Default) to calculate RWA. This can lead to more risk-sensitive RWA outcomes but requires significant investment in modeling capabilities and regulatory approval.
Q8: What is the minimum capital requirement based on RWA?
Under Basel II, banks must maintain a minimum total capital ratio of 8% of their total RWA. Tier 1 capital must be at least 4% of RWA. Our calculator shows an illustrative capital requirement based on this 8% minimum.
Understand the evolution from Basel II to the current regulatory standards.
var chartInstance = null; // Global variable to hold chart instance
function updateInputFields() {
var assetClass = document.getElementById("assetClass").value;
var dynamicInputsDiv = document.getElementById("dynamicInputs");
dynamicInputsDiv.innerHTML = ""; // Clear previous inputs
var html = "";
if (assetClass === "sovereign") {
html += `
The total value of the exposure.
AAA to AA-
A+ to A-
BBB+ to BBB-
BB+ to BB-
B+ to B-
CCC+ and below
Unrated
The credit rating assigned by a recognized credit rating agency.
`;
} else if (assetClass === "corporate") {
html += `
The total value of the exposure.
AAA to AA-
A+ to A-
BBB+ to BBB-
BB+ to BB-
B+ to B-
CCC+ and below
Unrated
The credit rating assigned by a recognized credit rating agency.
`;
} else if (assetClass === "retail") {
html += `
The total value of the exposure.
Yes (Standard 75% RW)
No (Standard 100% RW)
Does the exposure meet the Basel II definition of a qualifying retail exposure?
`;
} else if (assetClass === "residentialMortgage") {
html += `
The total value of the exposure.
The ratio of the loan amount to the property's appraised value.
`;
} else if (assetClass === "commercialMortgage") {
html += `
The total value of the exposure.
The ratio of the loan amount to the property's appraised value.
`;
} else if (assetClass === "equity") {
html += `
The total value of the equity exposure.
Listed, Publicly Traded
Unlisted, Venture Capital
Other
Classification of the equity investment.
`;
} else if (assetClass === "other") {
html += `
The total value of the exposure.
Manually enter the risk weight as per regulatory guidance or internal policy (typically 0-150%).
`;
}
dynamicInputsDiv.innerHTML = html;
calculateRiskWeights(); // Recalculate after updating inputs
}
function getInputValue(id, type = 'number') {
var element = document.getElementById(id);
if (!element) return null;
if (type === 'select') return element.value;
var value = parseFloat(element.value);
return isNaN(value) ? null : value;
}
function setErrorMessage(id, message) {
var errorElement = document.getElementById(id);
if (errorElement) {
if (message) {
errorElement.innerText = message;
errorElement.classList.add('visible');
} else {
errorElement.innerText = ";
errorElement.classList.remove('visible');
}
}
}
function calculateRiskWeights() {
var assetClass = document.getElementById("assetClass").value;
var exposureValue = 0;
var riskWeight = 0;
var error = false;
// Clear previous errors
var errorElements = document.querySelectorAll('.error-message');
for (var i = 0; i < errorElements.length; i++) {
errorElements[i].classList.remove('visible');
}
// Get Exposure Value and determine Risk Weight based on Asset Class
if (assetClass === "sovereign") {
exposureValue = getInputValue("exposureValueSovereign");
var rating = document.getElementById("creditRatingSovereign").value;
if (exposureValue === null) { setErrorMessage("exposureValueSovereignError", "Exposure value cannot be empty."); error = true; }
else if (exposureValue < 0) { setErrorMessage("exposureValueSovereignError", "Exposure value cannot be negative."); error = true; }
if (rating === "AAA_AA") riskWeight = 0;
else if (rating === "A_plus_A_minus") riskWeight = 20;
else if (rating === "BBB_plus_BBB_minus") riskWeight = 50;
else if (rating === "BB_plus_BB_minus") riskWeight = 100;
else if (rating === "B_plus_B_minus") riskWeight = 150;
else if (rating === "CCC_plus_below") riskWeight = 150; // Basel II often caps at 150% for lower rated
else if (rating === "Unrated") riskWeight = 50; // Default for unrated sovereigns might be 50% or higher depending on jurisdiction
} else if (assetClass === "corporate") {
exposureValue = getInputValue("exposureValueCorporate");
var rating = document.getElementById("creditRatingCorporate").value;
if (exposureValue === null) { setErrorMessage("exposureValueCorporateError", "Exposure value cannot be empty."); error = true; }
else if (exposureValue < 0) { setErrorMessage("exposureValueCorporateError", "Exposure value cannot be negative."); error = true; }
if (rating === "AAA_AA") riskWeight = 20;
else if (rating === "A_plus_A_minus") riskWeight = 50;
else if (rating === "BBB_plus_BBB_minus") riskWeight = 100;
else if (rating === "BB_plus_BB_minus") riskWeight = 100; // Standard corporate is 100%
else if (rating === "B_plus_B_minus") riskWeight = 100;
else if (rating === "CCC_plus_below") riskWeight = 100;
else if (rating === "Unrated") riskWeight = 100; // Standard for unrated corporates
} else if (assetClass === "retail") {
exposureValue = getInputValue("exposureValueRetail");
var criteria = document.getElementById("retailCriteria").value;
if (exposureValue === null) { setErrorMessage("exposureValueRetailError", "Exposure value cannot be empty."); error = true; }
else if (exposureValue < 0) { setErrorMessage("exposureValueRetailError", "Exposure value cannot be negative."); error = true; }
if (criteria === "yes") riskWeight = 75;
else riskWeight = 100; // Default for non-qualifying retail
} else if (assetClass === "residentialMortgage") {
exposureValue = getInputValue("exposureValueResidentialMortgage");
var ltv = getInputValue("ltvResidentialMortgage");
if (exposureValue === null) { setErrorMessage("exposureValueResidentialMortgageError", "Exposure value cannot be empty."); error = true; }
else if (exposureValue < 0) { setErrorMessage("exposureValueResidentialMortgageError", "Exposure value cannot be negative."); error = true; }
if (ltv === null) { setErrorMessage("ltvResidentialMortgageError", "LTV cannot be empty."); error = true; }
else if (ltv 100) { setErrorMessage("ltvResidentialMortgageError", "LTV must be between 0 and 100."); error = true; }
// Basel II standard approach for residential mortgages
if (ltv <= 75) riskWeight = 35;
else if (ltv <= 90) riskWeight = 50;
else if (ltv <= 100) riskWeight = 75;
else riskWeight = 100; // Fallback, though LTV should be capped at 100
} else if (assetClass === "commercialMortgage") {
exposureValue = getInputValue("exposureValueCommercialMortgage");
var ltv = getInputValue("ltvCommercialMortgage");
if (exposureValue === null) { setErrorMessage("exposureValueCommercialMortgageError", "Exposure value cannot be empty."); error = true; }
else if (exposureValue < 0) { setErrorMessage("exposureValueCommercialMortgageError", "Exposure value cannot be negative."); error = true; }
if (ltv === null) { setErrorMessage("ltvCommercialMortgageError", "LTV cannot be empty."); error = true; }
else if (ltv 100) { setErrorMessage("ltvCommercialMortgageError", "LTV must be between 0 and 100."); error = true; }
// Basel II standard approach for commercial mortgages is typically higher
if (ltv <= 60) riskWeight = 70; // Example values, actual can vary
else if (ltv <= 80) riskWeight = 90;
else riskWeight = 120; // Higher risk for higher LTV
} else if (assetClass === "equity") {
exposureValue = getInputValue("exposureValueEquity");
var equityType = document.getElementById("equityType").value;
if (exposureValue === null) { setErrorMessage("exposureValueEquityError", "Exposure value cannot be empty."); error = true; }
else if (exposureValue < 0) { setErrorMessage("exposureValueEquityError", "Exposure value cannot be negative."); error = true; }
// Basel II equity risk weights can be high
if (equityType === "listedPublic") riskWeight = 200; // Standard for listed equity
else if (equityType === "unlistedVenture") riskWeight = 300; // Higher for venture capital
else riskWeight = 400; // Default for other equity, can be very high
} else if (assetClass === "other") {
exposureValue = getInputValue("exposureValueOther");
riskWeight = getInputValue("riskWeightOther");
if (exposureValue === null) { setErrorMessage("exposureValueOtherError", "Exposure value cannot be empty."); error = true; }
else if (exposureValue < 0) { setErrorMessage("exposureValueOtherError", "Exposure value cannot be negative."); error = true; }
if (riskWeight === null) { setErrorMessage("riskWeightOtherError", "Risk weight cannot be empty."); error = true; }
else if (riskWeight 150) { setErrorMessage("riskWeightOtherError", "Risk weight must be between 0 and 150%."); error = true; }
}
var rwa = "–";
var capitalRequirement = "–";
if (!error) {
rwa = exposureValue * (riskWeight / 100);
// Illustrative Capital Requirement (assuming 8% CAR)
capitalRequirement = rwa * 0.08;
document.getElementById("intermediateResultRW").innerText = riskWeight.toFixed(2) + "%";
document.getElementById("intermediateResultEV").innerText = formatCurrency(exposureValue);
document.getElementById("intermediateResultCR").innerText = formatCurrency(capitalRequirement);
document.getElementById("primaryResultRWA").innerText = formatCurrency(rwa);
updateChart(riskWeight, capitalRequirement);
} else {
document.getElementById("intermediateResultRW").innerText = "–";
document.getElementById("intermediateResultEV").innerText = "–";
document.getElementById("intermediateResultCR").innerText = "–";
document.getElementById("primaryResultRWA").innerText = "–";
updateChart(0, 0); // Clear chart or show default state
}
}
function formatCurrency(amount) {
if (amount === "–") return "–";
// Basic currency formatting, adjust locale and options as needed
return amount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
function resetCalculator() {
document.getElementById("assetClass").value = "sovereign";
updateInputFields(); // This will reset inputs to their defaults
calculateRiskWeights(); // Ensure results are updated
}
function copyResults() {
var assetClass = document.getElementById("assetClass").value;
var rw = document.getElementById("intermediateResultRW").innerText;
var ev = document.getElementById("intermediateResultEV").innerText;
var cr = document.getElementById("intermediateResultCR").innerText;
var rwa = document.getElementById("primaryResultRWA").innerText;
var assumptions = "Asset Class: " + assetClass + "\n";
if (assetClass === "sovereign") {
assumptions += "Credit Rating: " + document.getElementById("creditRatingSovereign").selectedOptions[0].text + "\n";
} else if (assetClass === "corporate") {
assumptions += "Credit Rating: " + document.getElementById("creditRatingCorporate").selectedOptions[0].text + "\n";
} else if (assetClass === "retail") {
assumptions += "Retail Criteria Met: " + (document.getElementById("retailCriteria").value === "yes" ? "Yes" : "No") + "\n";
} else if (assetClass === "residentialMortgage") {
assumptions += "LTV Ratio: " + document.getElementById("ltvResidentialMortgage").value + "%\n";
} else if (assetClass === "commercialMortgage") {
assumptions += "LTV Ratio: " + document.getElementById("ltvCommercialMortgage").value + "%\n";
} else if (assetClass === "equity") {
assumptions += "Equity Type: " + document.getElementById("equityType").selectedOptions[0].text + "\n";
} else if (assetClass === "other") {
assumptions += "Assigned Risk Weight: " + document.getElementById("riskWeightOther").value + "%\n";
}
assumptions += "Illustrative Capital Requirement assumes 8% CAR.";
var textToCopy = "— Basel II Risk Weight Calculation Results —\n\n";
textToCopy += "Primary Result:\n";
textToCopy += "Risk-Weighted Assets (RWA): " + rwa + "\n\n";
textToCopy += "Key Intermediate Values:\n";
textToCopy += "Risk Weight: " + rw + "\n";
textToCopy += "Exposure Value: " + ev + "\n";
textToCopy += "Capital Requirement (Illustrative): " + cr + "\n\n";
textToCopy += "Key Assumptions:\n" + assumptions;
// Use a temporary textarea to copy text
var textArea = document.createElement("textarea");
textArea.value = textToCopy;
textArea.style.position = "fixed";
textArea.style.left = "-9999px";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'Results copied successfully!' : 'Failed to copy results.';
alert(msg); // Simple feedback
} catch (err) {
alert('Oops, unable to copy');
}
document.body.removeChild(textArea);
}
function updateChart(riskWeight, capitalRequirement) {
var ctx = document.getElementById('riskCapitalChart').getContext('2d');
// Define data points for the chart
// We'll show a range of risk weights and their corresponding capital requirements
var chartData = {
labels: [], // Risk Weights (%)
datasets: [
{
label: 'Capital Requirement (Illustrative @ 8% CAR)',
data: [], // Capital Requirement values
borderColor: 'var(–primary-color)',
backgroundColor: 'rgba(0, 74, 153, 0.2)',
fill: true,
tension: 0.1
}
]
};
// Generate data points for a range of risk weights
var minRW = 0;
var maxRW = 400; // Max possible RW for some equity types
var step = 25;
for (var rw = minRW; rw <= maxRW; rw += step) {
chartData.labels.push(rw + "%");
var illustrativeCapital = (1000000 * (rw / 100)) * 0.08; // Assuming a base exposure of 1M for illustration
chartData.datasets[0].data.push(illustrativeCapital);
}
// Add the current calculated point if it's not already covered by the steps
var currentRWPercent = parseFloat(riskWeight);
if (!chartData.labels.includes(currentRWPercent + "%")) {
chartData.labels.push(currentRWPercent + "%");
chartData.datasets[0].data.push(capitalRequirement);
// Sort labels and data to maintain order
var combined = [];
for (var i = 0; i item.label);
chartData.datasets[0].data = combined.map(item => item.value);
}
// Destroy previous chart instance if it exists
if (chartInstance) {
chartInstance.destroy();
}
// Create the chart
chartInstance = new Chart(ctx, {
type: 'line',
data: chartData,
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true,
title: {
display: true,
text: 'Illustrative Capital Requirement (Currency)'
},
ticks: {
callback: function(value, index, values) {
// Format y-axis labels as currency
return '$' + value.toLocaleString();
}
}
},
x: {
title: {
display: true,
text: 'Risk Weight (%)'
}
}
},
plugins: {
tooltip: {
callbacks: {
label: function(context) {
var label = context.dataset.label || ";
if (label) {
label += ': ';
}
if (context.parsed.y !== null) {
label += '$' + context.parsed.y.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
return label;
}
}
},
legend: {
display: true
}
}
}
});
}
// Initial setup
document.addEventListener('DOMContentLoaded', function() {
updateInputFields(); // Populate initial fields based on default asset class
calculateRiskWeights(); // Calculate initial results
});
// Add Chart.js library dynamically if not present (for standalone HTML)
// In a real WordPress environment, you'd enqueue this properly.
if (typeof Chart === 'undefined') {
var script = document.createElement('script');
script.src = 'https://cdn.jsdelivr.net/npm/chart.js@3.7.0/dist/chart.min.js';
script.onload = function() {
// Re-initialize chart after library loads if needed, or just ensure calculateRiskWeights is called
if (document.readyState === 'complete') {
updateInputFields();
calculateRiskWeights();
}
};
document.head.appendChild(script);
} else {
// Ensure chart is drawn on initial load if Chart.js is already available
updateInputFields();
calculateRiskWeights();
}