Skip to content

Add Value at Risk and Expected Shortfall to financial - #15051

Merged
cclauss merged 3 commits into
TheAlgorithms:masterfrom
shuxue6662-a11y:codex/financial-risk-metrics
Sep 21, 2026
Merged

cclauss merged 3 commits into
TheAlgorithms:masterfrom
shuxue6662-a11y:codex/financial-risk-metrics

Conversation

@shuxue6662-a11y

Copy link
Copy Markdown
Contributor

What changed

Adds two historical-simulation risk metrics to the financial directory:

  • value_at_risk.py -- Value at Risk (VaR) using the linearly interpolated quantile of observed returns (NumPy default, type 7). The result is the negative of the return quantile, so it is a positive loss magnitude when the tail contains losses.
  • expected_shortfall.py -- Expected Shortfall (ES / CVaR), the average loss beyond the VaR threshold. It captures the severity of tail losses that VaR alone misses and is a coherent risk measure.

Why

The financial directory already covers basic time-series and interest calculations, but it contains no risk measures. VaR and ES are the two most widely used risk metrics in portfolio management and regulatory risk control (for example Basel market-risk rules), and both fit the repository's pure-standard-library style.

Impact

Each module exposes a single, well-documented function that accepts a sequence of portfolio returns and a confidence level:

>>> value_at_risk([-10, -5, -2, 1, 4], 0.95)
9.0
>>> expected_shortfall([-10, -5, -2, 1, 4], 0.75)
7.5

Both functions validate erroneous inputs (empty sequences, non-finite values, and confidence levels outside (0, 1)) and include doctests for valid and invalid cases.

Checks

  • python -m doctest financial/value_at_risk.py financial/expected_shortfall.py -- all doctests pass
  • ruff check and ruff format --check -- pass
  • mypy --ignore-missing-imports financial/value_at_risk.py financial/expected_shortfall.py -- pass
  • pre-commit run --files financial/value_at_risk.py financial/expected_shortfall.py -- all hooks pass

@cclauss
cclauss enabled auto-merge (squash) September 21, 2026 16:53
@cclauss
cclauss disabled auto-merge September 21, 2026 16:54
@cclauss
cclauss merged commit 577c54c into TheAlgorithms:master Sep 21, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants