riskengine-var 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- riskengine_var-1.0.0/LICENSE +9 -0
- riskengine_var-1.0.0/PKG-INFO +13 -0
- riskengine_var-1.0.0/README.md +49 -0
- riskengine_var-1.0.0/pyproject.toml +18 -0
- riskengine_var-1.0.0/setup.cfg +4 -0
- riskengine_var-1.0.0/src/riskengine/__init__.py +14 -0
- riskengine_var-1.0.0/src/riskengine/backtest.py +74 -0
- riskengine_var-1.0.0/src/riskengine/cli.py +32 -0
- riskengine_var-1.0.0/src/riskengine/contribution.py +38 -0
- riskengine_var-1.0.0/src/riskengine/covariance.py +42 -0
- riskengine_var-1.0.0/src/riskengine/data.py +54 -0
- riskengine_var-1.0.0/src/riskengine/evt.py +34 -0
- riskengine_var-1.0.0/src/riskengine/factor.py +48 -0
- riskengine_var-1.0.0/src/riskengine/limits.py +56 -0
- riskengine_var-1.0.0/src/riskengine/metrics.py +34 -0
- riskengine_var-1.0.0/src/riskengine/portfolio.py +49 -0
- riskengine_var-1.0.0/src/riskengine/report.py +56 -0
- riskengine_var-1.0.0/src/riskengine/stress.py +64 -0
- riskengine_var-1.0.0/src/riskengine/var.py +121 -0
- riskengine_var-1.0.0/src/riskengine_var.egg-info/PKG-INFO +13 -0
- riskengine_var-1.0.0/src/riskengine_var.egg-info/SOURCES.txt +28 -0
- riskengine_var-1.0.0/src/riskengine_var.egg-info/dependency_links.txt +1 -0
- riskengine_var-1.0.0/src/riskengine_var.egg-info/entry_points.txt +2 -0
- riskengine_var-1.0.0/src/riskengine_var.egg-info/requires.txt +6 -0
- riskengine_var-1.0.0/src/riskengine_var.egg-info/top_level.txt +1 -0
- riskengine_var-1.0.0/tests/test_backtest_metrics.py +65 -0
- riskengine_var-1.0.0/tests/test_cov_contrib_factor.py +67 -0
- riskengine_var-1.0.0/tests/test_report_cli.py +19 -0
- riskengine_var-1.0.0/tests/test_stress_limits.py +66 -0
- riskengine_var-1.0.0/tests/test_var.py +72 -0
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 riskengine contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: riskengine-var
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Open-source portfolio market-risk engine: VaR/ES, EVT, factor risk, stress tests, limits, backtests
|
|
5
|
+
License: MIT
|
|
6
|
+
Requires-Python: >=3.9
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Dist: numpy>=1.23
|
|
9
|
+
Requires-Dist: scipy>=1.9
|
|
10
|
+
Requires-Dist: pandas>=1.5
|
|
11
|
+
Provides-Extra: dev
|
|
12
|
+
Requires-Dist: pytest; extra == "dev"
|
|
13
|
+
Dynamic: license-file
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# riskengine
|
|
2
|
+
|
|
3
|
+
An open-source portfolio **market-risk engine** in Python: Value-at-Risk and Expected Shortfall by seven methods, extreme value theory, covariance estimation, risk decomposition, factor risk, stress and reverse stress testing, limit monitoring, VaR/ES backtesting, and report generation.
|
|
4
|
+
|
|
5
|
+
It is a research and engineering-quality library. It is **not** a replacement for institutional platforms such as BlackRock Aladdin, which cover many asset classes, pricing models, proprietary data and regulatory workflows. See [docs/LIMITATIONS.md](docs/LIMITATIONS.md) before relying on any number.
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
| Area | What is included |
|
|
10
|
+
|---|---|
|
|
11
|
+
| VaR / ES | Historical, delta-normal, delta-Student-t, Cornish-Fisher, EWMA (RiskMetrics), filtered historical simulation, Monte Carlo (normal and multivariate-t), EVT peaks-over-threshold (GPD) |
|
|
12
|
+
| Covariance | Sample, EWMA, Ledoit-Wolf shrinkage, nearest-PSD repair |
|
|
13
|
+
| Decomposition | Euler component/marginal VaR (sums exactly to total), historical component ES, incremental VaR |
|
|
14
|
+
| Factor risk | OLS factor model, systematic vs idiosyncratic split, factor contributions, factor shocks |
|
|
15
|
+
| Stress | Custom scenarios, historical window replay, worst rolling windows, reverse stress test (closed-form minimum-distance shock) |
|
|
16
|
+
| Limits | Soft/hard limits, utilisation, alerts, position and concentration metrics |
|
|
17
|
+
| Backtesting | Rolling out-of-sample, Kupiec POF, Christoffersen independence and conditional coverage, Basel traffic light, Acerbi-Szekely ES test |
|
|
18
|
+
| Reporting | Markdown report, CLI |
|
|
19
|
+
| Data | Yahoo Finance loader with cache, synthetic fat-tailed generator |
|
|
20
|
+
|
|
21
|
+
## Install and run
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
pip install -e .[dev]
|
|
25
|
+
pytest -q # 54 tests
|
|
26
|
+
python examples/demo.py # offline demo
|
|
27
|
+
riskengine report --tickers SPY,TLT,GLD --values 500000,300000,200000
|
|
28
|
+
python examples/real_data_validation.py # backtests on real ETF data -> docs/VALIDATION.md
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from riskengine import *
|
|
33
|
+
pf = Portfolio({"SPY": 5e6, "TLT": 3e6}, returns_df) # returns_df: simple daily returns
|
|
34
|
+
historical_var_es(pf.pnl_series().values, 0.99) # VarResult(var, es, ...)
|
|
35
|
+
risk_contributions(pf.values, ledoit_wolf_cov(returns_df.values), 0.99, pf.assets)
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Validation
|
|
39
|
+
|
|
40
|
+
Correctness is tested against closed forms (normal VaR/ES, Euler allocation, reverse-stress optimality, Pareto tail index recovery) and by property tests (ES >= VaR, hedged pair has zero risk, no look-ahead in backtests). Model adequacy is tested on 20 years of real ETF data: see [docs/VALIDATION.md](docs/VALIDATION.md). Most models **fail** the conditional coverage test, and the docs say so.
|
|
41
|
+
|
|
42
|
+
## Documentation
|
|
43
|
+
|
|
44
|
+
- [docs/METHODOLOGY.md](docs/METHODOLOGY.md): formulas and conventions
|
|
45
|
+
- [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md): modules and data flow
|
|
46
|
+
- [docs/VALIDATION.md](docs/VALIDATION.md): real-data backtest results
|
|
47
|
+
- [docs/LIMITATIONS.md](docs/LIMITATIONS.md): what it does not do
|
|
48
|
+
|
|
49
|
+
Not investment advice. MIT licensed.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
[project]
|
|
5
|
+
name = "riskengine-var"
|
|
6
|
+
version = "1.0.0"
|
|
7
|
+
description = "Open-source portfolio market-risk engine: VaR/ES, EVT, factor risk, stress tests, limits, backtests"
|
|
8
|
+
requires-python = ">=3.9"
|
|
9
|
+
dependencies = ["numpy>=1.23", "scipy>=1.9", "pandas>=1.5"]
|
|
10
|
+
license = {text = "MIT"}
|
|
11
|
+
[project.optional-dependencies]
|
|
12
|
+
dev = ["pytest"]
|
|
13
|
+
[project.scripts]
|
|
14
|
+
riskengine = "riskengine.cli:main"
|
|
15
|
+
[tool.setuptools.packages.find]
|
|
16
|
+
where = ["src"]
|
|
17
|
+
[tool.pytest.ini_options]
|
|
18
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""riskengine: an open-source portfolio market-risk engine."""
|
|
2
|
+
from .portfolio import Portfolio
|
|
3
|
+
from .var import (historical_var_es, parametric_var_es, cornish_fisher_var,
|
|
4
|
+
ewma_var_es, filtered_historical_var_es, monte_carlo_var_es, VarResult)
|
|
5
|
+
from .evt import evt_var_es
|
|
6
|
+
from .covariance import sample_cov, ewma_cov, ledoit_wolf_cov, nearest_psd
|
|
7
|
+
from .contribution import risk_contributions
|
|
8
|
+
from .factor import FactorModel
|
|
9
|
+
from .stress import Scenario, apply_scenario, historical_scenario, reverse_stress
|
|
10
|
+
from .limits import Limit, LimitSet, check_limits
|
|
11
|
+
from .backtest import kupiec_pof, christoffersen_independence, christoffersen_cc, basel_traffic_light, backtest_var, es_backtest_acerbi_szekely
|
|
12
|
+
from .metrics import max_drawdown, sharpe, sortino, drawdown_series, summary_stats
|
|
13
|
+
from .report import build_report
|
|
14
|
+
__version__ = "1.0.0"
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""VaR/ES backtesting: Kupiec POF, Christoffersen independence & conditional coverage,
|
|
2
|
+
Basel traffic light, Acerbi-Szekely ES test (Z2)."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
import numpy as np
|
|
5
|
+
from scipy import stats
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _xlogy(x, y): return 0.0 if x == 0 else x * np.log(y)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def kupiec_pof(exceptions, confidence=0.99) -> dict:
|
|
12
|
+
e = np.asarray(exceptions, bool)
|
|
13
|
+
n, x = len(e), int(e.sum()); p = 1 - confidence
|
|
14
|
+
if n == 0: raise ValueError("empty")
|
|
15
|
+
ph = x / n
|
|
16
|
+
ll0 = _xlogy(n - x, 1 - p) + _xlogy(x, p)
|
|
17
|
+
ll1 = _xlogy(n - x, 1 - ph) + _xlogy(x, ph)
|
|
18
|
+
lr = -2 * (ll0 - ll1)
|
|
19
|
+
return {"n": n, "exceptions": x, "expected": n * p, "lr": float(lr), "p_value": float(1 - stats.chi2.cdf(lr, 1)),
|
|
20
|
+
"reject_5pct": bool(lr > stats.chi2.ppf(0.95, 1))}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def christoffersen_independence(exceptions) -> dict:
|
|
24
|
+
e = np.asarray(exceptions, int)
|
|
25
|
+
a, b = e[:-1], e[1:]
|
|
26
|
+
n00 = int(((a == 0) & (b == 0)).sum()); n01 = int(((a == 0) & (b == 1)).sum())
|
|
27
|
+
n10 = int(((a == 1) & (b == 0)).sum()); n11 = int(((a == 1) & (b == 1)).sum())
|
|
28
|
+
pi01 = n01 / max(n00 + n01, 1); pi11 = n11 / max(n10 + n11, 1)
|
|
29
|
+
pi = (n01 + n11) / max(n00 + n01 + n10 + n11, 1)
|
|
30
|
+
ll0 = _xlogy(n00 + n10, 1 - pi) + _xlogy(n01 + n11, pi)
|
|
31
|
+
ll1 = _xlogy(n00, 1 - pi01) + _xlogy(n01, pi01) + _xlogy(n10, 1 - pi11) + _xlogy(n11, pi11)
|
|
32
|
+
lr = max(-2 * (ll0 - ll1), 0.0)
|
|
33
|
+
return {"lr": float(lr), "p_value": float(1 - stats.chi2.cdf(lr, 1)), "reject_5pct": bool(lr > stats.chi2.ppf(0.95, 1))}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def christoffersen_cc(exceptions, confidence=0.99) -> dict:
|
|
37
|
+
k = kupiec_pof(exceptions, confidence); i = christoffersen_independence(exceptions)
|
|
38
|
+
lr = k["lr"] + i["lr"]
|
|
39
|
+
return {"lr": lr, "p_value": float(1 - stats.chi2.cdf(lr, 2)), "reject_5pct": bool(lr > stats.chi2.ppf(0.95, 2))}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def basel_traffic_light(exceptions_250d: int) -> str:
|
|
43
|
+
"""Basel II/III zones for 99% VaR over 250 days: green 0-4, yellow 5-9, red 10+."""
|
|
44
|
+
if exceptions_250d <= 4: return "green"
|
|
45
|
+
if exceptions_250d <= 9: return "yellow"
|
|
46
|
+
return "red"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def es_backtest_acerbi_szekely(pnl, var_forecast, es_forecast, confidence=0.99) -> dict:
|
|
50
|
+
"""Z2 statistic: E[Z2]=0 under correct model; negative => ES underestimated.
|
|
51
|
+
Z2 = sum(L_t * I_t / (ES_t)) / (T*(1-c)) - 1 using losses L_t."""
|
|
52
|
+
L = -np.asarray(pnl, float); v = np.asarray(var_forecast, float); es = np.asarray(es_forecast, float)
|
|
53
|
+
I = L > v
|
|
54
|
+
T = len(L)
|
|
55
|
+
z2 = float((L * I / es).sum() / (T * (1 - confidence)) - 1)
|
|
56
|
+
return {"z2": z2, "n_exceptions": int(I.sum()), "interpretation": "ES underestimated" if z2 > 0.0 else "ES adequate or conservative"}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def backtest_var(pnl, method, window=500, confidence=0.99, step=1) -> dict:
|
|
60
|
+
"""Rolling out-of-sample backtest. method(history_pnl, confidence)->VarResult.
|
|
61
|
+
Uses only data strictly before each test day (no look-ahead)."""
|
|
62
|
+
pnl = np.asarray(pnl, float)
|
|
63
|
+
if len(pnl) <= window: raise ValueError("series shorter than window")
|
|
64
|
+
vs, es, act = [], [], []
|
|
65
|
+
for t in range(window, len(pnl), step):
|
|
66
|
+
r = method(pnl[t - window:t], confidence)
|
|
67
|
+
vs.append(r.var); es.append(r.es); act.append(pnl[t])
|
|
68
|
+
vs, es, act = map(np.array, (vs, es, act))
|
|
69
|
+
exc = (-act) > vs
|
|
70
|
+
out = {"n": len(act), "exceptions": int(exc.sum()), "rate": float(exc.mean()),
|
|
71
|
+
"kupiec": kupiec_pof(exc, confidence), "independence": christoffersen_independence(exc),
|
|
72
|
+
"cc": christoffersen_cc(exc, confidence), "es_test": es_backtest_acerbi_szekely(act, vs, es, confidence),
|
|
73
|
+
"var": vs, "es": es, "pnl": act, "exceptions_flags": exc}
|
|
74
|
+
return out
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Command line: riskengine report --tickers SPY,TLT,GLD --values 500000,300000,200000"""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
import argparse, sys
|
|
4
|
+
from .data import fetch_yahoo_prices, to_returns, synthetic_returns
|
|
5
|
+
from .portfolio import Portfolio
|
|
6
|
+
from .report import build_report
|
|
7
|
+
from .limits import Limit, LimitSet
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def main(argv=None):
|
|
11
|
+
p = argparse.ArgumentParser(prog="riskengine")
|
|
12
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
13
|
+
r = sub.add_parser("report")
|
|
14
|
+
r.add_argument("--tickers"); r.add_argument("--values"); r.add_argument("--range", default="10y")
|
|
15
|
+
r.add_argument("--confidence", type=float, default=0.99); r.add_argument("--horizon", type=int, default=1)
|
|
16
|
+
r.add_argument("--synthetic", action="store_true"); r.add_argument("--cache", default=None)
|
|
17
|
+
a = p.parse_args(argv)
|
|
18
|
+
if a.synthetic:
|
|
19
|
+
rets = synthetic_returns(); vals = {c: 1e6 for c in rets.columns}
|
|
20
|
+
else:
|
|
21
|
+
t = a.tickers.split(","); v = [float(x) for x in a.values.split(",")]
|
|
22
|
+
if len(t) != len(v): sys.exit("tickers and values must match in length")
|
|
23
|
+
rets = to_returns(fetch_yahoo_prices(t, a.range, a.cache)); vals = dict(zip(t, v))
|
|
24
|
+
pf = Portfolio(vals, rets)
|
|
25
|
+
ls = LimitSet([Limit("1d VaR % NAV", "var_pct_nav", 0.03), Limit("Max position", "max_position_pct_gross", 0.5),
|
|
26
|
+
Limit("Model dispersion", "var_ratio_max_min", 2.0)])
|
|
27
|
+
print(build_report(pf, ls, a.confidence, a.horizon))
|
|
28
|
+
return 0
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
if __name__ == "__main__":
|
|
32
|
+
sys.exit(main())
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Risk decomposition: marginal, component, incremental contributions."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
import numpy as np
|
|
4
|
+
import pandas as pd
|
|
5
|
+
from scipy import stats
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def risk_contributions(values, cov, confidence=0.99, assets=None) -> pd.DataFrame:
|
|
9
|
+
"""Euler decomposition of delta-normal VaR. Component VaRs sum exactly to portfolio VaR."""
|
|
10
|
+
x = np.asarray(values, float); C = np.asarray(cov, float)
|
|
11
|
+
sd = np.sqrt(x @ C @ x)
|
|
12
|
+
z = stats.norm.ppf(confidence)
|
|
13
|
+
marginal = z * (C @ x) / sd # dVaR/dx_i
|
|
14
|
+
comp = x * marginal
|
|
15
|
+
df = pd.DataFrame({"value": x, "marginal_var": marginal, "component_var": comp,
|
|
16
|
+
"pct_contribution": comp / comp.sum()},
|
|
17
|
+
index=assets if assets is not None else range(len(x)))
|
|
18
|
+
return df
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def historical_es_contributions(pnl_matrix, values, confidence=0.99, assets=None) -> pd.DataFrame:
|
|
22
|
+
"""Component ES from historical scenarios: average asset P&L in the portfolio's tail days."""
|
|
23
|
+
P = np.asarray(pnl_matrix, float) * np.asarray(values, float)
|
|
24
|
+
port = P.sum(1)
|
|
25
|
+
thr = np.quantile(port, 1 - confidence)
|
|
26
|
+
tail = port <= thr
|
|
27
|
+
comp = -P[tail].mean(0)
|
|
28
|
+
return pd.DataFrame({"component_es": comp, "pct_contribution": comp / comp.sum()},
|
|
29
|
+
index=assets if assets is not None else range(P.shape[1]))
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def incremental_var(values, cov, i, confidence=0.99) -> float:
|
|
33
|
+
"""VaR change from removing position i entirely."""
|
|
34
|
+
x = np.asarray(values, float); C = np.asarray(cov, float)
|
|
35
|
+
z = stats.norm.ppf(confidence)
|
|
36
|
+
full = z * np.sqrt(x @ C @ x)
|
|
37
|
+
y = x.copy(); y[i] = 0
|
|
38
|
+
return float(full - z * np.sqrt(y @ C @ y))
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Covariance estimators."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def sample_cov(R) -> np.ndarray:
|
|
7
|
+
return np.cov(np.asarray(R, float), rowvar=False)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def ewma_cov(R, lam: float = 0.94) -> np.ndarray:
|
|
11
|
+
"""RiskMetrics exponentially weighted covariance (zero-mean)."""
|
|
12
|
+
X = np.asarray(R, float)
|
|
13
|
+
n = X.shape[0]
|
|
14
|
+
w = lam ** np.arange(n - 1, -1, -1)
|
|
15
|
+
w = w / w.sum()
|
|
16
|
+
return (X * w[:, None]).T @ X
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def ledoit_wolf_cov(R) -> np.ndarray:
|
|
20
|
+
"""Ledoit-Wolf (2004) shrinkage toward scaled identity."""
|
|
21
|
+
X = np.asarray(R, float)
|
|
22
|
+
n, p = X.shape
|
|
23
|
+
X = X - X.mean(0)
|
|
24
|
+
S = X.T @ X / n
|
|
25
|
+
mu = np.trace(S) / p
|
|
26
|
+
d2 = np.sum((S - mu * np.eye(p)) ** 2) / p
|
|
27
|
+
b2 = sum(np.sum((np.outer(x, x) - S) ** 2) for x in X) / (n * n) / p
|
|
28
|
+
b2 = min(b2, d2)
|
|
29
|
+
delta = b2 / d2 if d2 > 0 else 0.0
|
|
30
|
+
return delta * mu * np.eye(p) + (1 - delta) * S
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def nearest_psd(C, eps: float = 1e-10) -> np.ndarray:
|
|
34
|
+
"""Clip negative eigenvalues to make a symmetric matrix positive semi-definite."""
|
|
35
|
+
C = (C + C.T) / 2
|
|
36
|
+
w, V = np.linalg.eigh(C)
|
|
37
|
+
return (V * np.clip(w, eps, None)) @ V.T
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def corr_from_cov(C):
|
|
41
|
+
d = np.sqrt(np.diag(C))
|
|
42
|
+
return C / np.outer(d, d)
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Data loading: Yahoo Finance public chart endpoint (no key) with CSV cache, plus synthetic data."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
import json, os, urllib.request
|
|
4
|
+
import numpy as np
|
|
5
|
+
import pandas as pd
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def fetch_yahoo_prices(tickers, range_="10y", cache_dir=None, timeout=30) -> pd.DataFrame:
|
|
9
|
+
"""Download adjusted daily closes. Raises on failure. Data is for research use only."""
|
|
10
|
+
frames = {}
|
|
11
|
+
for t in tickers:
|
|
12
|
+
path = os.path.join(cache_dir, f"{t}_{range_}.csv") if cache_dir else None
|
|
13
|
+
if path and os.path.exists(path):
|
|
14
|
+
s = pd.read_csv(path, index_col=0, parse_dates=True).iloc[:, 0]
|
|
15
|
+
else:
|
|
16
|
+
url = f"https://query1.finance.yahoo.com/v8/finance/chart/{t}?range={range_}&interval=1d"
|
|
17
|
+
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
|
|
18
|
+
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
19
|
+
j = json.load(r)
|
|
20
|
+
res = j["chart"]["result"][0]
|
|
21
|
+
ts = pd.to_datetime(res["timestamp"], unit="s").normalize()
|
|
22
|
+
adj = res["indicators"].get("adjclose", [{}])[0].get("adjclose") or res["indicators"]["quote"][0]["close"]
|
|
23
|
+
s = pd.Series(adj, index=ts, name=t, dtype=float)
|
|
24
|
+
s = s[~s.index.duplicated(keep="last")]
|
|
25
|
+
if path:
|
|
26
|
+
os.makedirs(cache_dir, exist_ok=True)
|
|
27
|
+
s.to_csv(path)
|
|
28
|
+
frames[t] = s.rename(t)
|
|
29
|
+
return pd.concat(frames.values(), axis=1).dropna(how="all").ffill().dropna()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def to_returns(prices: pd.DataFrame, log: bool = False) -> pd.DataFrame:
|
|
33
|
+
r = np.log(prices / prices.shift(1)) if log else prices.pct_change()
|
|
34
|
+
return r.dropna(how="any")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def synthetic_returns(n_days=2500, n_assets=6, seed=0, df=5, vol_clusters=True) -> pd.DataFrame:
|
|
38
|
+
"""Correlated fat-tailed returns with GARCH-like volatility clustering (for tests/demos)."""
|
|
39
|
+
rng = np.random.default_rng(seed)
|
|
40
|
+
A = rng.normal(size=(n_assets, n_assets))
|
|
41
|
+
C = A @ A.T + n_assets * np.eye(n_assets)
|
|
42
|
+
d = np.sqrt(np.diag(C)); C = C / np.outer(d, d)
|
|
43
|
+
L = np.linalg.cholesky(C)
|
|
44
|
+
base = np.linspace(0.008, 0.015, n_assets)
|
|
45
|
+
z = rng.standard_t(df, size=(n_days, n_assets)) / np.sqrt(df / (df - 2))
|
|
46
|
+
z = z @ L.T
|
|
47
|
+
out = np.empty_like(z)
|
|
48
|
+
h = np.ones(n_assets)
|
|
49
|
+
for t in range(n_days):
|
|
50
|
+
out[t] = z[t] * base * np.sqrt(h) + 0.0003
|
|
51
|
+
if vol_clusters:
|
|
52
|
+
h = 0.05 + 0.1 * (out[t] / base) ** 2 + 0.85 * h
|
|
53
|
+
idx = pd.bdate_range("2010-01-01", periods=n_days)
|
|
54
|
+
return pd.DataFrame(out, index=idx, columns=[f"A{i}" for i in range(n_assets)])
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Extreme value theory: peaks-over-threshold with a Generalised Pareto tail."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
import numpy as np
|
|
4
|
+
from scipy import stats
|
|
5
|
+
from .var import VarResult
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def evt_var_es(pnl, confidence=0.99, threshold_q=0.95, horizon=1) -> VarResult:
|
|
9
|
+
"""POT-GPD VaR/ES (McNeil-Frey). Needs enough exceedances (>=30) to be meaningful."""
|
|
10
|
+
losses = -np.asarray(pnl, float)
|
|
11
|
+
u = np.quantile(losses, threshold_q)
|
|
12
|
+
exc = losses[losses > u] - u
|
|
13
|
+
if len(exc) < 30:
|
|
14
|
+
raise ValueError(f"only {len(exc)} exceedances; lower threshold_q or add data")
|
|
15
|
+
xi, _, beta = stats.genpareto.fit(exc, floc=0)
|
|
16
|
+
n, nu = len(losses), len(exc)
|
|
17
|
+
ratio = (1 - confidence) * n / nu
|
|
18
|
+
if abs(xi) < 1e-6:
|
|
19
|
+
var = u - beta * np.log(ratio)
|
|
20
|
+
else:
|
|
21
|
+
var = u + beta / xi * (ratio ** (-xi) - 1)
|
|
22
|
+
if xi >= 1:
|
|
23
|
+
raise ValueError("fitted tail index xi>=1: ES infinite")
|
|
24
|
+
es = (var + beta - xi * u) / (1 - xi)
|
|
25
|
+
s = np.sqrt(horizon)
|
|
26
|
+
return VarResult(float(max(var, 0)) * s, float(max(es, 0)) * s, confidence, horizon, "evt-gpd")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def tail_index(pnl, threshold_q=0.95):
|
|
30
|
+
losses = -np.asarray(pnl, float)
|
|
31
|
+
u = np.quantile(losses, threshold_q)
|
|
32
|
+
exc = losses[losses > u] - u
|
|
33
|
+
xi, _, beta = stats.genpareto.fit(exc, floc=0)
|
|
34
|
+
return {"xi": float(xi), "beta": float(beta), "threshold": float(u), "n_exceedances": int(len(exc))}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Linear factor risk model."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
import numpy as np
|
|
4
|
+
import pandas as pd
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class FactorModel:
|
|
8
|
+
"""r_i = alpha_i + B_i f + e_i, fitted by OLS per asset.
|
|
9
|
+
|
|
10
|
+
Portfolio variance = (b'F b) + sum(x_i^2 s_i^2); systematic vs idiosyncratic split.
|
|
11
|
+
"""
|
|
12
|
+
def __init__(self, asset_returns: pd.DataFrame, factor_returns: pd.DataFrame):
|
|
13
|
+
idx = asset_returns.index.intersection(factor_returns.index)
|
|
14
|
+
if len(idx) < 3 * (factor_returns.shape[1] + 1):
|
|
15
|
+
raise ValueError("too few overlapping observations")
|
|
16
|
+
Y = asset_returns.loc[idx].values; F = factor_returns.loc[idx].values
|
|
17
|
+
X = np.column_stack([np.ones(len(idx)), F])
|
|
18
|
+
coef, *_ = np.linalg.lstsq(X, Y, rcond=None)
|
|
19
|
+
self.assets = list(asset_returns.columns); self.factors = list(factor_returns.columns)
|
|
20
|
+
self.alpha = coef[0]; self.B = coef[1:].T # assets x factors
|
|
21
|
+
resid = Y - X @ coef
|
|
22
|
+
dof = len(idx) - X.shape[1]
|
|
23
|
+
self.idio_var = (resid ** 2).sum(0) / dof
|
|
24
|
+
ss_res = (resid ** 2).sum(0); ss_tot = ((Y - Y.mean(0)) ** 2).sum(0)
|
|
25
|
+
self.r2 = 1 - ss_res / ss_tot
|
|
26
|
+
self.F_cov = np.cov(F, rowvar=False).reshape(F.shape[1], F.shape[1])
|
|
27
|
+
|
|
28
|
+
def exposures(self) -> pd.DataFrame:
|
|
29
|
+
return pd.DataFrame(self.B, index=self.assets, columns=self.factors)
|
|
30
|
+
|
|
31
|
+
def asset_cov(self) -> np.ndarray:
|
|
32
|
+
return self.B @ self.F_cov @ self.B.T + np.diag(self.idio_var)
|
|
33
|
+
|
|
34
|
+
def decompose(self, values) -> dict:
|
|
35
|
+
x = np.asarray(values, float)
|
|
36
|
+
b = self.B.T @ x # portfolio factor exposure (currency)
|
|
37
|
+
sys_var = float(b @ self.F_cov @ b)
|
|
38
|
+
idio = float((x ** 2 * self.idio_var).sum())
|
|
39
|
+
tot = sys_var + idio
|
|
40
|
+
fc = b * (self.F_cov @ b) # Euler factor contributions to systematic variance
|
|
41
|
+
return {"total_vol": tot ** 0.5, "systematic_vol": sys_var ** 0.5, "idiosyncratic_vol": idio ** 0.5,
|
|
42
|
+
"systematic_share": sys_var / tot, "factor_exposure": pd.Series(b, index=self.factors),
|
|
43
|
+
"factor_variance_share": pd.Series(fc / tot, index=self.factors),
|
|
44
|
+
"idio_share": idio / tot}
|
|
45
|
+
|
|
46
|
+
def factor_shock_pnl(self, values, shocks: dict) -> float:
|
|
47
|
+
f = np.array([shocks.get(k, 0.0) for k in self.factors])
|
|
48
|
+
return float(np.asarray(values) @ (self.B @ f))
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""Risk limits and alerts."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@dataclass
|
|
8
|
+
class Limit:
|
|
9
|
+
name: str
|
|
10
|
+
metric: str # key in the metrics dict
|
|
11
|
+
hard: float # breach threshold (metric must be <= hard)
|
|
12
|
+
soft: float | None = None # warning threshold (default 80% of hard)
|
|
13
|
+
|
|
14
|
+
def evaluate(self, value: float) -> dict:
|
|
15
|
+
soft = self.soft if self.soft is not None else 0.8 * self.hard
|
|
16
|
+
if value > self.hard: status = "BREACH"
|
|
17
|
+
elif value > soft: status = "WARNING"
|
|
18
|
+
else: status = "OK"
|
|
19
|
+
return {"limit": self.name, "metric": self.metric, "value": float(value), "soft": soft,
|
|
20
|
+
"hard": self.hard, "utilisation": float(value / self.hard) if self.hard else float("inf"),
|
|
21
|
+
"status": status}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class LimitSet:
|
|
26
|
+
limits: list
|
|
27
|
+
|
|
28
|
+
def check(self, metrics: dict) -> list:
|
|
29
|
+
out = []
|
|
30
|
+
for l in self.limits:
|
|
31
|
+
if l.metric not in metrics:
|
|
32
|
+
raise KeyError(f"metric '{l.metric}' not provided for limit '{l.name}'")
|
|
33
|
+
out.append(l.evaluate(metrics[l.metric]))
|
|
34
|
+
return out
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def position_metrics(portfolio) -> dict:
|
|
38
|
+
w = np.abs(portfolio.values) / portfolio.gross
|
|
39
|
+
return {"max_position_pct_gross": float(w.max()), "gross_to_nav": portfolio.gross / portfolio.nav,
|
|
40
|
+
"hhi": float((w ** 2).sum()), "n_positions": len(w)}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def check_limits(limit_set: LimitSet, metrics: dict) -> dict:
|
|
44
|
+
res = limit_set.check(metrics)
|
|
45
|
+
return {"results": res, "breaches": [r for r in res if r["status"] == "BREACH"],
|
|
46
|
+
"warnings": [r for r in res if r["status"] == "WARNING"],
|
|
47
|
+
"ok": all(r["status"] != "BREACH" for r in res)}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def format_alerts(report: dict) -> list:
|
|
51
|
+
msgs = []
|
|
52
|
+
for r in report["breaches"]:
|
|
53
|
+
msgs.append(f"[BREACH] {r['limit']}: {r['value']:.4g} > hard limit {r['hard']:.4g} ({r['utilisation']:.0%})")
|
|
54
|
+
for r in report["warnings"]:
|
|
55
|
+
msgs.append(f"[WARN] {r['limit']}: {r['value']:.4g} above soft limit {r['soft']:.4g} ({r['utilisation']:.0%})")
|
|
56
|
+
return msgs
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Performance and drawdown metrics."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
import numpy as np
|
|
4
|
+
import pandas as pd
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def drawdown_series(returns) -> pd.Series:
|
|
8
|
+
r = pd.Series(returns)
|
|
9
|
+
wealth = (1 + r).cumprod()
|
|
10
|
+
return wealth / wealth.cummax() - 1
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def max_drawdown(returns) -> float:
|
|
14
|
+
return float(drawdown_series(returns).min())
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def sharpe(returns, rf=0.0, periods=252) -> float:
|
|
18
|
+
r = np.asarray(returns, float) - rf / periods
|
|
19
|
+
sd = r.std(ddof=1)
|
|
20
|
+
return float(r.mean() / sd * np.sqrt(periods)) if sd > 0 else float("nan")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def sortino(returns, rf=0.0, periods=252) -> float:
|
|
24
|
+
r = np.asarray(returns, float) - rf / periods
|
|
25
|
+
dd = np.sqrt(np.mean(np.minimum(r, 0) ** 2))
|
|
26
|
+
return float(r.mean() / dd * np.sqrt(periods)) if dd > 0 else float("nan")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def summary_stats(returns, periods=252) -> dict:
|
|
30
|
+
r = pd.Series(returns).dropna()
|
|
31
|
+
return {"ann_return": float((1 + r).prod() ** (periods / len(r)) - 1), "ann_vol": float(r.std(ddof=1) * np.sqrt(periods)),
|
|
32
|
+
"sharpe": sharpe(r, periods=periods), "sortino": sortino(r, periods=periods),
|
|
33
|
+
"max_drawdown": max_drawdown(r), "skew": float(r.skew()), "excess_kurtosis": float(r.kurt()),
|
|
34
|
+
"worst_day": float(r.min()), "best_day": float(r.max()), "n": int(len(r))}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Portfolio container."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
import numpy as np
|
|
5
|
+
import pandas as pd
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass
|
|
9
|
+
class Portfolio:
|
|
10
|
+
"""Holdings as market values (currency units). Weights derive from them.
|
|
11
|
+
|
|
12
|
+
returns: DataFrame of simple periodic asset returns (columns match holdings keys).
|
|
13
|
+
"""
|
|
14
|
+
holdings: dict
|
|
15
|
+
returns: pd.DataFrame
|
|
16
|
+
name: str = "portfolio"
|
|
17
|
+
meta: dict = field(default_factory=dict)
|
|
18
|
+
|
|
19
|
+
def __post_init__(self):
|
|
20
|
+
missing = [k for k in self.holdings if k not in self.returns.columns]
|
|
21
|
+
if missing:
|
|
22
|
+
raise ValueError(f"no returns for: {missing}")
|
|
23
|
+
if not np.isfinite(list(self.holdings.values())).all():
|
|
24
|
+
raise ValueError("non-finite holding")
|
|
25
|
+
if self.returns.isna().any().any():
|
|
26
|
+
raise ValueError("returns contain NaN")
|
|
27
|
+
self.returns = self.returns[list(self.holdings)]
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def assets(self): return list(self.holdings)
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def values(self) -> np.ndarray: return np.array([self.holdings[a] for a in self.assets], float)
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def nav(self) -> float: return float(self.values.sum())
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def gross(self) -> float: return float(np.abs(self.values).sum())
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def weights(self) -> np.ndarray: return self.values / self.nav
|
|
43
|
+
|
|
44
|
+
def pnl_series(self) -> pd.Series:
|
|
45
|
+
"""Historical P&L of today's holdings (static positions)."""
|
|
46
|
+
return pd.Series(self.returns.values @ self.values, index=self.returns.index, name="pnl")
|
|
47
|
+
|
|
48
|
+
def return_series(self) -> pd.Series:
|
|
49
|
+
return self.pnl_series() / self.nav
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""Markdown risk report builder."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
import numpy as np
|
|
4
|
+
from .var import historical_var_es, parametric_var_es, monte_carlo_var_es, cornish_fisher_var, filtered_historical_var_es
|
|
5
|
+
from .evt import evt_var_es
|
|
6
|
+
from .covariance import ledoit_wolf_cov
|
|
7
|
+
from .contribution import risk_contributions
|
|
8
|
+
from .stress import run_scenarios, STANDARD_SCENARIOS, worst_windows
|
|
9
|
+
from .limits import position_metrics, check_limits, format_alerts
|
|
10
|
+
from .metrics import summary_stats
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _fmt(x): return f"{x:,.0f}"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def build_report(portfolio, limit_set=None, confidence=0.99, horizon=1, seed=1, scenarios=None, factor_model=None) -> str:
|
|
17
|
+
pnl = portfolio.pnl_series().values
|
|
18
|
+
C = ledoit_wolf_cov(portfolio.returns.values)
|
|
19
|
+
ms = [historical_var_es(pnl, confidence, horizon),
|
|
20
|
+
parametric_var_es(portfolio.values, C, confidence, horizon),
|
|
21
|
+
parametric_var_es(portfolio.values, C, confidence, horizon, dist="t", df=5),
|
|
22
|
+
cornish_fisher_var(pnl, confidence, horizon),
|
|
23
|
+
filtered_historical_var_es(portfolio.return_series().values, portfolio.nav, confidence, horizon),
|
|
24
|
+
monte_carlo_var_es(portfolio.values, C, confidence, horizon, 200_000, "t", 5, seed=seed)]
|
|
25
|
+
try: ms.append(evt_var_es(pnl, confidence, horizon=horizon))
|
|
26
|
+
except ValueError: pass
|
|
27
|
+
L = [f"# Risk report: {portfolio.name}", "",
|
|
28
|
+
f"NAV {_fmt(portfolio.nav)} | gross {_fmt(portfolio.gross)} | {len(portfolio.returns)} observations "
|
|
29
|
+
f"({portfolio.returns.index[0].date()} to {portfolio.returns.index[-1].date()})", "",
|
|
30
|
+
f"## VaR / ES ({confidence:.0%}, {horizon}-day)", "", "| Method | VaR | ES | VaR % NAV |", "|---|---:|---:|---:|"]
|
|
31
|
+
for m in ms: L.append(f"| {m.method} | {_fmt(m.var)} | {_fmt(m.es)} | {m.var / portfolio.nav:.2%} |")
|
|
32
|
+
L += ["", "Methods disagree by design; the spread is itself a model-risk indicator.", "",
|
|
33
|
+
"## Risk contributions (delta-normal VaR)", "", "| Asset | Value | Component VaR | % of risk |", "|---|---:|---:|---:|"]
|
|
34
|
+
rc = risk_contributions(portfolio.values, C, confidence, portfolio.assets)
|
|
35
|
+
for a, r in rc.iterrows(): L.append(f"| {a} | {_fmt(r.value)} | {_fmt(r.component_var)} | {r.pct_contribution:.1%} |")
|
|
36
|
+
L += ["", "## Stress scenarios", "", "| Scenario | P&L | % NAV |", "|---|---:|---:|"]
|
|
37
|
+
for n, r in run_scenarios(portfolio, scenarios or STANDARD_SCENARIOS).iterrows():
|
|
38
|
+
L.append(f"| {n} | {_fmt(r.pnl)} | {r.pnl_pct_nav:.1%} |")
|
|
39
|
+
ww = worst_windows(portfolio, 10, 3)
|
|
40
|
+
L += ["", "Worst historical 10-day windows (current holdings):", ""]
|
|
41
|
+
for _, r in ww.iterrows(): L.append(f"- ending {r['end']}: {_fmt(r.pnl)} ({r.pnl_pct_nav:.1%})")
|
|
42
|
+
if factor_model is not None:
|
|
43
|
+
d = factor_model.decompose(portfolio.values)
|
|
44
|
+
L += ["", "## Factor risk", "", f"Systematic share of variance: {d['systematic_share']:.1%}; idiosyncratic {d['idio_share']:.1%}", ""]
|
|
45
|
+
for f, v in d["factor_variance_share"].items(): L.append(f"- {f}: {v:.1%}")
|
|
46
|
+
s = summary_stats(portfolio.return_series())
|
|
47
|
+
L += ["", "## Realised statistics", "", f"Ann. return {s['ann_return']:.2%}, vol {s['ann_vol']:.2%}, Sharpe {s['sharpe']:.2f}, max drawdown {s['max_drawdown']:.2%}, excess kurtosis {s['excess_kurtosis']:.1f}"]
|
|
48
|
+
if limit_set is not None:
|
|
49
|
+
metrics = {**position_metrics(portfolio), "var_pct_nav": ms[0].var / portfolio.nav, "es_pct_nav": ms[0].es / portfolio.nav,
|
|
50
|
+
"var_ratio_max_min": max(m.var for m in ms) / min(m.var for m in ms)}
|
|
51
|
+
rep = check_limits(limit_set, metrics)
|
|
52
|
+
L += ["", "## Limits", ""] + [f"- {a}" for a in format_alerts(rep)] + ([] if (rep["breaches"] or rep["warnings"]) else ["- all limits OK"])
|
|
53
|
+
L += ["", "## Caveats", "", "- Static positions; linear (delta-one) instruments only. No options, bonds, FX conversion or liquidity adjustment.",
|
|
54
|
+
"- Multi-day horizons use square-root-of-time scaling, which understates risk under volatility clustering/autocorrelation.",
|
|
55
|
+
"- Results depend on the history window and are not a regulatory capital figure."]
|
|
56
|
+
return "\n".join(L)
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Stress testing: user scenarios, historical replays, reverse stress tests."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
import numpy as np
|
|
5
|
+
import pandas as pd
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass
|
|
9
|
+
class Scenario:
|
|
10
|
+
name: str
|
|
11
|
+
shocks: dict # asset -> simple return shock, e.g. {"SPY": -0.2}
|
|
12
|
+
default_shock: float = 0.0 # applied to assets not listed
|
|
13
|
+
description: str = ""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def apply_scenario(portfolio, scenario: Scenario) -> dict:
|
|
17
|
+
s = np.array([scenario.shocks.get(a, scenario.default_shock) for a in portfolio.assets])
|
|
18
|
+
pnl_by = portfolio.values * s
|
|
19
|
+
return {"scenario": scenario.name, "pnl": float(pnl_by.sum()), "pnl_pct_nav": float(pnl_by.sum() / portfolio.nav),
|
|
20
|
+
"by_asset": pd.Series(pnl_by, index=portfolio.assets)}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def run_scenarios(portfolio, scenarios) -> pd.DataFrame:
|
|
24
|
+
rows = [apply_scenario(portfolio, s) for s in scenarios]
|
|
25
|
+
return pd.DataFrame([{k: r[k] for k in ("scenario", "pnl", "pnl_pct_nav")} for r in rows]).set_index("scenario")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def historical_scenario(portfolio, start, end) -> dict:
|
|
29
|
+
"""Replay the compounded asset returns over [start, end] on current holdings."""
|
|
30
|
+
w = portfolio.returns.loc[start:end]
|
|
31
|
+
if len(w) == 0: raise ValueError("empty window")
|
|
32
|
+
cum = (1 + w).prod() - 1
|
|
33
|
+
pnl = float((cum.values * portfolio.values).sum())
|
|
34
|
+
return {"start": str(w.index[0].date()), "end": str(w.index[-1].date()), "pnl": pnl, "pnl_pct_nav": pnl / portfolio.nav}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def worst_windows(portfolio, window=10, top=5) -> pd.DataFrame:
|
|
38
|
+
"""Worst non-overlapping rolling `window`-day P&L windows in history."""
|
|
39
|
+
pnl = portfolio.pnl_series()
|
|
40
|
+
roll = ((1 + portfolio.return_series()).rolling(window).apply(np.prod, raw=True) - 1) * portfolio.nav
|
|
41
|
+
roll = roll.dropna().sort_values()
|
|
42
|
+
picked, out = [], []
|
|
43
|
+
for d, v in roll.items():
|
|
44
|
+
if all(abs((d - p).days) > window * 1.5 for p in picked):
|
|
45
|
+
picked.append(d); out.append({"end": d.date(), "pnl": float(v), "pnl_pct_nav": float(v / portfolio.nav)})
|
|
46
|
+
if len(out) >= top: break
|
|
47
|
+
return pd.DataFrame(out)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def reverse_stress(values, cov, target_loss, assets=None) -> pd.Series:
|
|
51
|
+
"""Most likely shock vector (min Mahalanobis distance) producing `target_loss` P&L loss.
|
|
52
|
+
|
|
53
|
+
Solves min s'C^-1 s s.t. x's = -target_loss -> s = -L * C x / (x'Cx).
|
|
54
|
+
"""
|
|
55
|
+
x = np.asarray(values, float); C = np.asarray(cov, float)
|
|
56
|
+
s = -target_loss * (C @ x) / (x @ C @ x)
|
|
57
|
+
return pd.Series(s, index=assets if assets is not None else range(len(x)))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
STANDARD_SCENARIOS = [
|
|
61
|
+
Scenario("equity_crash_-20", {}, default_shock=-0.20, description="Uniform -20% shock"),
|
|
62
|
+
Scenario("equity_crash_-40", {}, default_shock=-0.40, description="Uniform -40% shock (GFC-scale)"),
|
|
63
|
+
Scenario("rally_+10", {}, default_shock=0.10, description="Uniform +10%"),
|
|
64
|
+
]
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""Value-at-Risk and Expected Shortfall. All results are positive loss numbers in currency units
|
|
2
|
+
(or return units when computed from a return series via `scale=1`).
|
|
3
|
+
Convention: confidence c=0.99 means the loss exceeded with probability 1-c."""
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
import numpy as np
|
|
7
|
+
from scipy import stats
|
|
8
|
+
from .covariance import ewma_cov, nearest_psd
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class VarResult:
|
|
13
|
+
var: float
|
|
14
|
+
es: float
|
|
15
|
+
confidence: float
|
|
16
|
+
horizon: int
|
|
17
|
+
method: str
|
|
18
|
+
|
|
19
|
+
def as_dict(self): return self.__dict__.copy()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _check(c):
|
|
23
|
+
if not 0.5 < c < 1: raise ValueError("confidence must be in (0.5,1)")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _hz(h): return np.sqrt(h)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _var_es_from_losses(losses, c):
|
|
30
|
+
losses = np.sort(np.asarray(losses, float))
|
|
31
|
+
n = len(losses)
|
|
32
|
+
k = int(np.ceil(c * n)) - 1
|
|
33
|
+
var = losses[min(k, n - 1)]
|
|
34
|
+
tail = losses[losses >= var]
|
|
35
|
+
es = tail.mean() if len(tail) else var
|
|
36
|
+
return float(max(var, 0.0)), float(max(es, 0.0))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def historical_var_es(pnl, confidence=0.99, horizon=1) -> VarResult:
|
|
40
|
+
"""Empirical VaR/ES from a P&L series. Horizon via square-root-of-time (an approximation)."""
|
|
41
|
+
_check(confidence)
|
|
42
|
+
v, e = _var_es_from_losses(-np.asarray(pnl, float), confidence)
|
|
43
|
+
return VarResult(v * _hz(horizon), e * _hz(horizon), confidence, horizon, "historical")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def parametric_var_es(values, cov, confidence=0.99, horizon=1, mean=None, dist="normal", df=6) -> VarResult:
|
|
47
|
+
"""Delta-normal (or Student-t scaled) VaR. values: position values, cov: return covariance."""
|
|
48
|
+
_check(confidence)
|
|
49
|
+
x = np.asarray(values, float); C = np.asarray(cov, float)
|
|
50
|
+
sd = float(np.sqrt(x @ C @ x)) * _hz(horizon)
|
|
51
|
+
mu = 0.0 if mean is None else float(np.asarray(mean) @ x) * horizon
|
|
52
|
+
if dist == "normal":
|
|
53
|
+
z = stats.norm.ppf(confidence)
|
|
54
|
+
var = z * sd - mu
|
|
55
|
+
es = sd * stats.norm.pdf(z) / (1 - confidence) - mu
|
|
56
|
+
elif dist == "t":
|
|
57
|
+
if df <= 2: raise ValueError("df must be >2")
|
|
58
|
+
sc = np.sqrt((df - 2) / df)
|
|
59
|
+
q = stats.t.ppf(confidence, df)
|
|
60
|
+
var = sc * q * sd - mu
|
|
61
|
+
es = sc * sd * (stats.t.pdf(q, df) / (1 - confidence)) * (df + q * q) / (df - 1) - mu
|
|
62
|
+
else:
|
|
63
|
+
raise ValueError("dist must be normal|t")
|
|
64
|
+
return VarResult(float(max(var, 0)), float(max(es, 0)), confidence, horizon, f"parametric-{dist}")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def cornish_fisher_var(pnl, confidence=0.99, horizon=1) -> VarResult:
|
|
68
|
+
"""Cornish-Fisher VaR adjusting the normal quantile for sample skew/kurtosis."""
|
|
69
|
+
_check(confidence)
|
|
70
|
+
r = np.asarray(pnl, float)
|
|
71
|
+
mu, sd = r.mean(), r.std(ddof=1)
|
|
72
|
+
s, k = stats.skew(r), stats.kurtosis(r)
|
|
73
|
+
z = stats.norm.ppf(1 - confidence)
|
|
74
|
+
zc = z + (z**2 - 1) * s / 6 + (z**3 - 3 * z) * k / 24 - (2 * z**3 - 5 * z) * s**2 / 36
|
|
75
|
+
var = -(mu + zc * sd)
|
|
76
|
+
h, e = _var_es_from_losses(-r, confidence)
|
|
77
|
+
return VarResult(float(max(var, 0)) * _hz(horizon), e * _hz(horizon), confidence, horizon, "cornish-fisher")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def ewma_var_es(values, returns, confidence=0.99, horizon=1, lam=0.94) -> VarResult:
|
|
81
|
+
r = parametric_var_es(values, ewma_cov(returns, lam), confidence, horizon)
|
|
82
|
+
r.method = f"ewma-{lam}"
|
|
83
|
+
return r
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def filtered_historical_var_es(pnl_returns, nav, confidence=0.99, horizon=1, lam=0.94) -> VarResult:
|
|
87
|
+
"""Volatility-filtered historical simulation (Hull-White): rescale returns to current EWMA vol."""
|
|
88
|
+
r = np.asarray(pnl_returns, float)
|
|
89
|
+
var_t = np.empty_like(r); var_t[0] = r[:20].var() if len(r) > 20 else r.var()
|
|
90
|
+
for t in range(1, len(r)):
|
|
91
|
+
var_t[t] = lam * var_t[t - 1] + (1 - lam) * r[t - 1] ** 2
|
|
92
|
+
sig = np.sqrt(var_t)
|
|
93
|
+
nxt = np.sqrt(lam * var_t[-1] + (1 - lam) * r[-1] ** 2)
|
|
94
|
+
scaled = r / sig * nxt
|
|
95
|
+
v, e = _var_es_from_losses(-scaled * nav, confidence)
|
|
96
|
+
return VarResult(v * _hz(horizon), e * _hz(horizon), confidence, horizon, "filtered-historical")
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def monte_carlo_var_es(values, cov, confidence=0.99, horizon=1, n_sims=100_000, dist="normal",
|
|
100
|
+
df=5, mean=None, seed=None) -> VarResult:
|
|
101
|
+
"""Monte Carlo with multivariate normal or multivariate-t (scaled to the same covariance)."""
|
|
102
|
+
_check(confidence)
|
|
103
|
+
pnl = simulate_pnl(values, cov, horizon, n_sims, dist, df, mean, seed)
|
|
104
|
+
v, e = _var_es_from_losses(-pnl, confidence)
|
|
105
|
+
return VarResult(v, e, confidence, horizon, f"monte-carlo-{dist}")
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def simulate_pnl(values, cov, horizon=1, n_sims=100_000, dist="normal", df=5, mean=None, seed=None):
|
|
109
|
+
rng = np.random.default_rng(seed)
|
|
110
|
+
x = np.asarray(values, float)
|
|
111
|
+
C = nearest_psd(np.asarray(cov, float)) * horizon
|
|
112
|
+
L = np.linalg.cholesky(C + 1e-14 * np.eye(len(x)))
|
|
113
|
+
z = rng.standard_normal((n_sims, len(x)))
|
|
114
|
+
if dist == "t":
|
|
115
|
+
w = rng.chisquare(df, n_sims) / df
|
|
116
|
+
z = z / np.sqrt(w)[:, None] * np.sqrt((df - 2) / df)
|
|
117
|
+
elif dist != "normal":
|
|
118
|
+
raise ValueError("dist must be normal|t")
|
|
119
|
+
rets = z @ L.T
|
|
120
|
+
if mean is not None: rets = rets + np.asarray(mean) * horizon
|
|
121
|
+
return rets @ x
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: riskengine-var
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Open-source portfolio market-risk engine: VaR/ES, EVT, factor risk, stress tests, limits, backtests
|
|
5
|
+
License: MIT
|
|
6
|
+
Requires-Python: >=3.9
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Dist: numpy>=1.23
|
|
9
|
+
Requires-Dist: scipy>=1.9
|
|
10
|
+
Requires-Dist: pandas>=1.5
|
|
11
|
+
Provides-Extra: dev
|
|
12
|
+
Requires-Dist: pytest; extra == "dev"
|
|
13
|
+
Dynamic: license-file
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/riskengine/__init__.py
|
|
5
|
+
src/riskengine/backtest.py
|
|
6
|
+
src/riskengine/cli.py
|
|
7
|
+
src/riskengine/contribution.py
|
|
8
|
+
src/riskengine/covariance.py
|
|
9
|
+
src/riskengine/data.py
|
|
10
|
+
src/riskengine/evt.py
|
|
11
|
+
src/riskengine/factor.py
|
|
12
|
+
src/riskengine/limits.py
|
|
13
|
+
src/riskengine/metrics.py
|
|
14
|
+
src/riskengine/portfolio.py
|
|
15
|
+
src/riskengine/report.py
|
|
16
|
+
src/riskengine/stress.py
|
|
17
|
+
src/riskengine/var.py
|
|
18
|
+
src/riskengine_var.egg-info/PKG-INFO
|
|
19
|
+
src/riskengine_var.egg-info/SOURCES.txt
|
|
20
|
+
src/riskengine_var.egg-info/dependency_links.txt
|
|
21
|
+
src/riskengine_var.egg-info/entry_points.txt
|
|
22
|
+
src/riskengine_var.egg-info/requires.txt
|
|
23
|
+
src/riskengine_var.egg-info/top_level.txt
|
|
24
|
+
tests/test_backtest_metrics.py
|
|
25
|
+
tests/test_cov_contrib_factor.py
|
|
26
|
+
tests/test_report_cli.py
|
|
27
|
+
tests/test_stress_limits.py
|
|
28
|
+
tests/test_var.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
riskengine
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import numpy as np, pytest
|
|
2
|
+
from riskengine import *
|
|
3
|
+
from riskengine.var import historical_var_es
|
|
4
|
+
|
|
5
|
+
def test_kupiec_accepts_correct_rate():
|
|
6
|
+
e = np.zeros(1000, bool); e[:10] = True
|
|
7
|
+
assert not kupiec_pof(e, 0.99)["reject_5pct"]
|
|
8
|
+
|
|
9
|
+
def test_kupiec_rejects_too_many():
|
|
10
|
+
e = np.zeros(1000, bool); e[:40] = True
|
|
11
|
+
r = kupiec_pof(e, 0.99); assert r["reject_5pct"] and r["p_value"] < 0.001
|
|
12
|
+
|
|
13
|
+
def test_kupiec_zero_exceptions_no_nan():
|
|
14
|
+
assert np.isfinite(kupiec_pof(np.zeros(250, bool))["lr"])
|
|
15
|
+
|
|
16
|
+
def test_independence_detects_clustering():
|
|
17
|
+
e = np.zeros(1000, bool); e[100:110] = True
|
|
18
|
+
assert christoffersen_independence(e)["reject_5pct"]
|
|
19
|
+
spread = np.zeros(1000, bool); spread[::100] = True
|
|
20
|
+
assert not christoffersen_independence(spread)["reject_5pct"]
|
|
21
|
+
|
|
22
|
+
def test_cc_combines():
|
|
23
|
+
e = np.zeros(1000, bool); e[100:130] = True
|
|
24
|
+
assert christoffersen_cc(e)["reject_5pct"]
|
|
25
|
+
|
|
26
|
+
def test_traffic_light():
|
|
27
|
+
assert [basel_traffic_light(i) for i in (0, 4, 5, 9, 10)] == ["green", "green", "yellow", "yellow", "red"]
|
|
28
|
+
|
|
29
|
+
def test_backtest_iid_normal_well_calibrated():
|
|
30
|
+
pnl = np.random.default_rng(7).normal(0, 1, 6000)
|
|
31
|
+
bt = backtest_var(pnl, historical_var_es, window=1000, confidence=0.95)
|
|
32
|
+
assert bt["rate"] == pytest.approx(0.05, abs=0.012)
|
|
33
|
+
assert not bt["kupiec"]["reject_5pct"]
|
|
34
|
+
|
|
35
|
+
def test_backtest_no_lookahead():
|
|
36
|
+
pnl = np.random.default_rng(0).normal(0, 1, 800); seen = []
|
|
37
|
+
def m(h, c): seen.append(len(h)); return historical_var_es(h, c)
|
|
38
|
+
backtest_var(pnl, m, window=500)
|
|
39
|
+
assert all(s == 500 for s in seen) and len(seen) == 300
|
|
40
|
+
|
|
41
|
+
def test_backtest_detects_underestimating_model():
|
|
42
|
+
rng = np.random.default_rng(3)
|
|
43
|
+
pnl = np.concatenate([rng.normal(0, 1, 1500), rng.normal(0, 3, 500)]) # vol regime shift
|
|
44
|
+
bt = backtest_var(pnl, historical_var_es, window=500, confidence=0.99)
|
|
45
|
+
assert bt["kupiec"]["reject_5pct"] and bt["es_test"]["z2"] > 0
|
|
46
|
+
|
|
47
|
+
def test_fhs_beats_static_hs_under_vol_clustering():
|
|
48
|
+
from riskengine.data import synthetic_returns
|
|
49
|
+
r = synthetic_returns(4000, 1, seed=11).iloc[:, 0].values * 1e6
|
|
50
|
+
hs = backtest_var(r, historical_var_es, 500, 0.99)
|
|
51
|
+
fh = backtest_var(r, lambda h, c: filtered_historical_var_es(h / 1e6, 1e6, c), 500, 0.99)
|
|
52
|
+
assert fh["independence"]["lr"] < hs["independence"]["lr"]
|
|
53
|
+
|
|
54
|
+
def test_es_test_perfect_model_near_zero():
|
|
55
|
+
rng = np.random.default_rng(1); x = rng.normal(0, 1, 200_000)
|
|
56
|
+
from scipy import stats
|
|
57
|
+
z = stats.norm.ppf(0.99); v = np.full_like(x, z); es = np.full_like(x, stats.norm.pdf(z) / 0.01)
|
|
58
|
+
assert abs(es_backtest_acerbi_szekely(x, v, es, 0.99)["z2"]) < 0.05
|
|
59
|
+
|
|
60
|
+
def test_metrics():
|
|
61
|
+
r = np.array([0.1, -0.5, 0.2])
|
|
62
|
+
assert max_drawdown(r) == pytest.approx(-0.5)
|
|
63
|
+
assert drawdown_series(r).iloc[0] == 0
|
|
64
|
+
assert np.isnan(sharpe(np.zeros(10)))
|
|
65
|
+
assert summary_stats(np.random.default_rng(0).normal(0.0005, 0.01, 500))["n"] == 500
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import numpy as np, pandas as pd, pytest
|
|
2
|
+
from riskengine import *
|
|
3
|
+
from riskengine.contribution import incremental_var, historical_es_contributions
|
|
4
|
+
from riskengine.covariance import corr_from_cov
|
|
5
|
+
|
|
6
|
+
def test_cov_psd_and_symmetric(rets):
|
|
7
|
+
for C in (sample_cov(rets.values), ewma_cov(rets.values), ledoit_wolf_cov(rets.values)):
|
|
8
|
+
assert np.allclose(C, C.T); assert np.linalg.eigvalsh(C).min() > 0
|
|
9
|
+
|
|
10
|
+
def test_ledoit_wolf_improves_conditioning_small_sample(rets):
|
|
11
|
+
X = rets.values[:40]
|
|
12
|
+
assert np.linalg.cond(ledoit_wolf_cov(X)) < np.linalg.cond(sample_cov(X))
|
|
13
|
+
|
|
14
|
+
def test_ewma_lambda_one_equals_second_moment():
|
|
15
|
+
X = np.random.default_rng(0).normal(size=(500, 3))
|
|
16
|
+
assert np.allclose(ewma_cov(X, 1.0), X.T @ X / 500)
|
|
17
|
+
|
|
18
|
+
def test_nearest_psd_fixes_bad_matrix():
|
|
19
|
+
C = np.array([[1, 0.9, -0.9], [0.9, 1, 0.9], [-0.9, 0.9, 1]])
|
|
20
|
+
assert np.linalg.eigvalsh(C).min() < 0
|
|
21
|
+
assert np.linalg.eigvalsh(nearest_psd(C)).min() >= 0
|
|
22
|
+
|
|
23
|
+
def test_euler_contributions_sum_to_var(pf):
|
|
24
|
+
C = sample_cov(pf.returns.values)
|
|
25
|
+
rc = risk_contributions(pf.values, C, 0.99, pf.assets)
|
|
26
|
+
assert rc.component_var.sum() == pytest.approx(parametric_var_es(pf.values, C, 0.99).var)
|
|
27
|
+
assert rc.pct_contribution.sum() == pytest.approx(1)
|
|
28
|
+
|
|
29
|
+
def test_marginal_var_matches_finite_difference(pf):
|
|
30
|
+
C = sample_cov(pf.returns.values); x = pf.values; h = 1.0
|
|
31
|
+
base = parametric_var_es(x, C).var; y = x.copy(); y[2] += h
|
|
32
|
+
fd = (parametric_var_es(y, C).var - base) / h
|
|
33
|
+
assert fd == pytest.approx(risk_contributions(x, C).marginal_var.iloc[2], rel=1e-4)
|
|
34
|
+
|
|
35
|
+
def test_incremental_var_positive_for_long_only(pf):
|
|
36
|
+
C = sample_cov(pf.returns.values)
|
|
37
|
+
assert incremental_var(pf.values, C, 0) > 0
|
|
38
|
+
|
|
39
|
+
def test_hist_es_contrib_sums(pf):
|
|
40
|
+
out = historical_es_contributions(pf.returns.values, pf.values, 0.95, pf.assets)
|
|
41
|
+
assert out.pct_contribution.sum() == pytest.approx(1)
|
|
42
|
+
|
|
43
|
+
def test_hedged_pair_has_zero_risk():
|
|
44
|
+
C = np.array([[1e-4, 1e-4], [1e-4, 1e-4]])
|
|
45
|
+
assert parametric_var_es([1e6, -1e6], C).var == pytest.approx(0, abs=1e-6)
|
|
46
|
+
|
|
47
|
+
def test_factor_model_recovers_betas():
|
|
48
|
+
rng = np.random.default_rng(0); n = 4000
|
|
49
|
+
f = pd.DataFrame(rng.normal(0, 0.01, (n, 2)), columns=["mkt", "val"])
|
|
50
|
+
B = np.array([[1.0, 0.5], [0.8, -0.3], [1.2, 0.0]])
|
|
51
|
+
a = pd.DataFrame(f.values @ B.T + rng.normal(0, 0.003, (n, 3)), columns=list("XYZ"))
|
|
52
|
+
fm = FactorModel(a, f)
|
|
53
|
+
assert np.allclose(fm.B, B, atol=0.05)
|
|
54
|
+
d = fm.decompose([1e6, 1e6, 1e6])
|
|
55
|
+
assert d["systematic_share"] + d["idio_share"] == pytest.approx(1)
|
|
56
|
+
assert d["factor_variance_share"].sum() == pytest.approx(d["systematic_share"])
|
|
57
|
+
assert np.allclose(np.diag(fm.asset_cov()), a.var().values, rtol=0.1)
|
|
58
|
+
|
|
59
|
+
def test_factor_shock_pnl_linear():
|
|
60
|
+
rng = np.random.default_rng(1); n = 1000
|
|
61
|
+
f = pd.DataFrame(rng.normal(0, 0.01, (n, 1)), columns=["mkt"])
|
|
62
|
+
a = pd.DataFrame({"X": 1.5 * f["mkt"] + rng.normal(0, 0.001, n)})
|
|
63
|
+
assert FactorModel(a, f).factor_shock_pnl([1000], {"mkt": -0.1}) == pytest.approx(-150, rel=0.05)
|
|
64
|
+
|
|
65
|
+
def test_factor_model_too_few_obs():
|
|
66
|
+
f = pd.DataFrame(np.zeros((5, 2)), columns=["a", "b"]);
|
|
67
|
+
with pytest.raises(ValueError): FactorModel(f.copy(), f)
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
from riskengine import *
|
|
3
|
+
from riskengine.cli import main
|
|
4
|
+
|
|
5
|
+
def test_report_contains_sections(pf, capsys):
|
|
6
|
+
ls = LimitSet([Limit("pos", "max_position_pct_gross", 0.2), Limit("var", "var_pct_nav", 0.5)])
|
|
7
|
+
t = build_report(pf, ls)
|
|
8
|
+
for s in ["VaR / ES", "Risk contributions", "Stress scenarios", "Limits", "Caveats", "historical", "evt-gpd"]:
|
|
9
|
+
assert s in t
|
|
10
|
+
assert "[BREACH] pos" in t
|
|
11
|
+
|
|
12
|
+
def test_report_deterministic(pf): assert build_report(pf, seed=5) == build_report(pf, seed=5)
|
|
13
|
+
|
|
14
|
+
def test_cli_synthetic(capsys):
|
|
15
|
+
assert main(["report", "--synthetic"]) == 0
|
|
16
|
+
assert "Risk report" in capsys.readouterr().out
|
|
17
|
+
|
|
18
|
+
def test_cli_length_mismatch():
|
|
19
|
+
with pytest.raises(SystemExit): main(["report", "--tickers", "A,B", "--values", "1"])
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import numpy as np, pandas as pd, pytest
|
|
2
|
+
from riskengine import *
|
|
3
|
+
from riskengine.stress import run_scenarios, worst_windows, STANDARD_SCENARIOS
|
|
4
|
+
from riskengine.limits import position_metrics, format_alerts
|
|
5
|
+
|
|
6
|
+
def test_scenario_pnl(pf):
|
|
7
|
+
r = apply_scenario(pf, Scenario("x", {"A0": -0.5}, default_shock=0.1))
|
|
8
|
+
exp = -0.5 * pf.holdings["A0"] + 0.1 * (pf.nav - pf.holdings["A0"])
|
|
9
|
+
assert r["pnl"] == pytest.approx(exp)
|
|
10
|
+
assert r["by_asset"].sum() == pytest.approx(r["pnl"])
|
|
11
|
+
|
|
12
|
+
def test_run_scenarios_table(pf):
|
|
13
|
+
t = run_scenarios(pf, STANDARD_SCENARIOS)
|
|
14
|
+
assert t.loc["equity_crash_-20", "pnl_pct_nav"] == pytest.approx(-0.2)
|
|
15
|
+
|
|
16
|
+
def test_historical_scenario_compounding(pf):
|
|
17
|
+
w = pf.returns.index[10], pf.returns.index[20]
|
|
18
|
+
r = historical_scenario(pf, *w)
|
|
19
|
+
cum = (1 + pf.returns.loc[w[0]:w[1]]).prod() - 1
|
|
20
|
+
assert r["pnl"] == pytest.approx((cum.values * pf.values).sum())
|
|
21
|
+
|
|
22
|
+
def test_historical_scenario_empty(pf):
|
|
23
|
+
with pytest.raises(ValueError): historical_scenario(pf, "1900-01-01", "1900-02-01")
|
|
24
|
+
|
|
25
|
+
def test_worst_windows_sorted_nonoverlap(pf):
|
|
26
|
+
w = worst_windows(pf, 10, 4)
|
|
27
|
+
assert list(w.pnl) == sorted(w.pnl) and (w.pnl < 0).all()
|
|
28
|
+
|
|
29
|
+
def test_reverse_stress_hits_target(pf):
|
|
30
|
+
C = sample_cov(pf.returns.values); s = reverse_stress(pf.values, C, 5e6)
|
|
31
|
+
assert (pf.values @ s.values) == pytest.approx(-5e6)
|
|
32
|
+
|
|
33
|
+
def test_reverse_stress_is_min_distance(pf):
|
|
34
|
+
C = sample_cov(pf.returns.values); Ci = np.linalg.inv(C); s = reverse_stress(pf.values, C, 1e6).values
|
|
35
|
+
rng = np.random.default_rng(0)
|
|
36
|
+
for _ in range(20):
|
|
37
|
+
d = rng.normal(size=len(s)); d -= pf.values * (d @ pf.values) / (pf.values @ pf.values) # keep x's fixed
|
|
38
|
+
t = s + 1e-3 * d
|
|
39
|
+
assert t @ Ci @ t >= s @ Ci @ s - 1e-9
|
|
40
|
+
|
|
41
|
+
def test_limit_status_levels():
|
|
42
|
+
l = Limit("v", "m", hard=10, soft=8)
|
|
43
|
+
assert l.evaluate(7)["status"] == "OK" and l.evaluate(9)["status"] == "WARNING" and l.evaluate(11)["status"] == "BREACH"
|
|
44
|
+
|
|
45
|
+
def test_default_soft_80pct():
|
|
46
|
+
assert Limit("v", "m", 10).evaluate(8.5)["status"] == "WARNING"
|
|
47
|
+
|
|
48
|
+
def test_check_limits_and_alerts(pf):
|
|
49
|
+
ls = LimitSet([Limit("pos", "max_position_pct_gross", 0.2), Limit("n", "n_positions", 100)])
|
|
50
|
+
rep = check_limits(ls, position_metrics(pf))
|
|
51
|
+
assert not rep["ok"] and len(rep["breaches"]) == 1
|
|
52
|
+
assert format_alerts(rep)[0].startswith("[BREACH]")
|
|
53
|
+
|
|
54
|
+
def test_missing_metric_raises():
|
|
55
|
+
with pytest.raises(KeyError): LimitSet([Limit("a", "zzz", 1)]).check({})
|
|
56
|
+
|
|
57
|
+
def test_position_metrics_hhi_equal_weights():
|
|
58
|
+
from riskengine.portfolio import Portfolio
|
|
59
|
+
r = pd.DataFrame(np.zeros((5, 4)), columns=list("abcd"))
|
|
60
|
+
m = position_metrics(Portfolio({c: 100 for c in "abcd"}, r))
|
|
61
|
+
assert m["hhi"] == pytest.approx(0.25)
|
|
62
|
+
|
|
63
|
+
def test_portfolio_validation(rets):
|
|
64
|
+
with pytest.raises(ValueError): Portfolio({"nope": 1}, rets)
|
|
65
|
+
bad = rets.copy(); bad.iloc[0, 0] = np.nan
|
|
66
|
+
with pytest.raises(ValueError): Portfolio({"A0": 1}, bad)
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import numpy as np, pytest
|
|
2
|
+
from scipy import stats
|
|
3
|
+
from riskengine import *
|
|
4
|
+
from riskengine.var import simulate_pnl
|
|
5
|
+
|
|
6
|
+
def test_historical_known_quantile():
|
|
7
|
+
pnl = -np.arange(1, 101, dtype=float) # losses 1..100
|
|
8
|
+
r = historical_var_es(pnl, 0.95)
|
|
9
|
+
assert r.var == 95 and r.es == pytest.approx(np.mean(range(95, 101)))
|
|
10
|
+
|
|
11
|
+
def test_parametric_normal_closed_form():
|
|
12
|
+
C = np.array([[0.0004]]); r = parametric_var_es([1e6], C, 0.99)
|
|
13
|
+
assert r.var == pytest.approx(1e6 * 0.02 * stats.norm.ppf(0.99))
|
|
14
|
+
z = stats.norm.ppf(0.99)
|
|
15
|
+
assert r.es == pytest.approx(1e6 * 0.02 * stats.norm.pdf(z) / 0.01)
|
|
16
|
+
|
|
17
|
+
def test_es_geq_var_all_methods(pf):
|
|
18
|
+
pnl = pf.pnl_series().values; C = sample_cov(pf.returns.values)
|
|
19
|
+
for r in [historical_var_es(pnl), parametric_var_es(pf.values, C), parametric_var_es(pf.values, C, dist="t"),
|
|
20
|
+
cornish_fisher_var(pnl), filtered_historical_var_es(pf.return_series().values, pf.nav),
|
|
21
|
+
monte_carlo_var_es(pf.values, C, seed=1), evt_var_es(pnl)]:
|
|
22
|
+
assert r.es >= r.var > 0
|
|
23
|
+
|
|
24
|
+
def test_horizon_sqrt_scaling():
|
|
25
|
+
pnl = np.random.default_rng(0).normal(0, 1, 2000)
|
|
26
|
+
assert historical_var_es(pnl, 0.99, 10).var == pytest.approx(historical_var_es(pnl, 0.99, 1).var * np.sqrt(10))
|
|
27
|
+
|
|
28
|
+
def test_monte_carlo_matches_parametric_normal(pf):
|
|
29
|
+
C = sample_cov(pf.returns.values)
|
|
30
|
+
mc = monte_carlo_var_es(pf.values, C, 0.99, n_sims=400_000, seed=3)
|
|
31
|
+
pa = parametric_var_es(pf.values, C, 0.99)
|
|
32
|
+
assert mc.var == pytest.approx(pa.var, rel=0.02)
|
|
33
|
+
assert mc.es == pytest.approx(pa.es, rel=0.03)
|
|
34
|
+
|
|
35
|
+
def test_mc_t_has_same_variance_fatter_tail():
|
|
36
|
+
C = np.array([[1e-4]]); sims = simulate_pnl([1.0], C, 1, 400_000, "t", 4, seed=1)
|
|
37
|
+
assert sims.std() == pytest.approx(0.01, rel=0.05)
|
|
38
|
+
assert monte_carlo_var_es([1.0], C, 0.999, n_sims=400_000, dist="t", df=4, seed=1).var > \
|
|
39
|
+
monte_carlo_var_es([1.0], C, 0.999, n_sims=400_000, seed=1).var
|
|
40
|
+
|
|
41
|
+
def test_parametric_t_es_exceeds_normal_deep_tail():
|
|
42
|
+
C = np.array([[1e-4]])
|
|
43
|
+
assert parametric_var_es([1], C, 0.999, dist="t", df=4).es > parametric_var_es([1], C, 0.999).es
|
|
44
|
+
|
|
45
|
+
def test_cornish_fisher_reduces_to_normal_for_gaussian():
|
|
46
|
+
x = np.random.default_rng(1).normal(0, 0.01, 200_000)
|
|
47
|
+
assert cornish_fisher_var(x, 0.99).var == pytest.approx(stats.norm.ppf(0.99) * 0.01, rel=0.03)
|
|
48
|
+
|
|
49
|
+
def test_fhs_scales_with_current_vol():
|
|
50
|
+
rng = np.random.default_rng(0)
|
|
51
|
+
calm = rng.normal(0, 0.005, 1000); hot = np.concatenate([calm, rng.normal(0, 0.03, 30)])
|
|
52
|
+
assert filtered_historical_var_es(hot, 1.0).var > 2 * filtered_historical_var_es(calm, 1.0).var
|
|
53
|
+
|
|
54
|
+
def test_evt_recovers_pareto_tail():
|
|
55
|
+
rng = np.random.default_rng(5)
|
|
56
|
+
x = -(rng.pareto(3.0, 20000) + 1) * 0.01 # alpha=3 -> xi=1/3
|
|
57
|
+
from riskengine.evt import tail_index
|
|
58
|
+
assert tail_index(x)["xi"] == pytest.approx(1 / 3, abs=0.08)
|
|
59
|
+
true_var = 0.01 * (0.01) ** (-1 / 3)
|
|
60
|
+
assert evt_var_es(x, 0.99).var == pytest.approx(true_var, rel=0.1)
|
|
61
|
+
|
|
62
|
+
def test_evt_too_few_data():
|
|
63
|
+
with pytest.raises(ValueError): evt_var_es(np.random.default_rng(0).normal(size=100))
|
|
64
|
+
|
|
65
|
+
def test_invalid_confidence():
|
|
66
|
+
with pytest.raises(ValueError): historical_var_es([1, 2, 3], 1.2)
|
|
67
|
+
|
|
68
|
+
def test_ewma_responds_to_recent_vol(rets):
|
|
69
|
+
v = np.ones(rets.shape[1]) * 1e6
|
|
70
|
+
base = ewma_var_es(v, rets.values).var
|
|
71
|
+
shocked = rets.values.copy(); shocked[-20:] *= 4
|
|
72
|
+
assert ewma_var_es(v, shocked).var > base
|