riskengine-var 1.0.0__py3-none-any.whl
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/__init__.py +14 -0
- riskengine/backtest.py +74 -0
- riskengine/cli.py +32 -0
- riskengine/contribution.py +38 -0
- riskengine/covariance.py +42 -0
- riskengine/data.py +54 -0
- riskengine/evt.py +34 -0
- riskengine/factor.py +48 -0
- riskengine/limits.py +56 -0
- riskengine/metrics.py +34 -0
- riskengine/portfolio.py +49 -0
- riskengine/report.py +56 -0
- riskengine/stress.py +64 -0
- riskengine/var.py +121 -0
- riskengine_var-1.0.0.dist-info/METADATA +13 -0
- riskengine_var-1.0.0.dist-info/RECORD +20 -0
- riskengine_var-1.0.0.dist-info/WHEEL +5 -0
- riskengine_var-1.0.0.dist-info/entry_points.txt +2 -0
- riskengine_var-1.0.0.dist-info/licenses/LICENSE +9 -0
- riskengine_var-1.0.0.dist-info/top_level.txt +1 -0
riskengine/__init__.py
ADDED
|
@@ -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"
|
riskengine/backtest.py
ADDED
|
@@ -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
|
riskengine/cli.py
ADDED
|
@@ -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))
|
riskengine/covariance.py
ADDED
|
@@ -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)
|
riskengine/data.py
ADDED
|
@@ -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)])
|
riskengine/evt.py
ADDED
|
@@ -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))}
|
riskengine/factor.py
ADDED
|
@@ -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))
|
riskengine/limits.py
ADDED
|
@@ -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
|
riskengine/metrics.py
ADDED
|
@@ -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))}
|
riskengine/portfolio.py
ADDED
|
@@ -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
|
riskengine/report.py
ADDED
|
@@ -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)
|
riskengine/stress.py
ADDED
|
@@ -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
|
+
]
|
riskengine/var.py
ADDED
|
@@ -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,20 @@
|
|
|
1
|
+
riskengine/__init__.py,sha256=RbdkNO8DmVrEwYMfE1BQmSHV6MpAMzzyo5nrx4D3ZyA,856
|
|
2
|
+
riskengine/backtest.py,sha256=uD7wT9j5FW-sMzBvTEu0uRkOfGHRD2CQxdO3XHBCwhM,3597
|
|
3
|
+
riskengine/cli.py,sha256=x9U4jOAFg1Z7y-nYqNGv0Tklr3cD0O2Dn1FfOA5GPhs,1508
|
|
4
|
+
riskengine/contribution.py,sha256=Jn9QcKHlKSByM06A-J0FqlUzYe8BtZRiIH5Y_KHPEXM,1670
|
|
5
|
+
riskengine/covariance.py,sha256=7vy5350vQFAesHPjXEpub_gnsDMemc-VbmghVcSnpLg,1206
|
|
6
|
+
riskengine/data.py,sha256=ZeCAIXUZVm8z1ZVp0S8nTd4UPugQQhtM8yKFbEPsuKk,2584
|
|
7
|
+
riskengine/evt.py,sha256=kRIzDIzpll9gYSU3DTLBue26F1UHM-9tubAgViI6dag,1381
|
|
8
|
+
riskengine/factor.py,sha256=k7I49En6wrBB66CxOIljqgNt-0a7Ggy9VNLGespITwc,2365
|
|
9
|
+
riskengine/limits.py,sha256=tCxc1oXmeavgMZf9rAqv_BjLKff3AEm3rAg-ozkIdzA,2123
|
|
10
|
+
riskengine/metrics.py,sha256=7xTK00tTM8CV89dR98euyL98it4XfRFJFPtvpBYF2no,1278
|
|
11
|
+
riskengine/portfolio.py,sha256=xePnEQbbCzJ4Kc_VLv6oQrVILbiqbebk_fNvLALoLfo,1633
|
|
12
|
+
riskengine/report.py,sha256=bvxkWmBjXxa5_s0DxqpElMVUSPsW-0EVDwTFWl_x_yY,4108
|
|
13
|
+
riskengine/stress.py,sha256=_9p-ZAZ2wtt-FjPtfUrxPEMWQ41WgE9ycv6HeVnzQTs,2847
|
|
14
|
+
riskengine/var.py,sha256=IjiqyHmg3vHDUXhM1KuM8IEfaijh4vU8DoyhLp1hkNs,4974
|
|
15
|
+
riskengine_var-1.0.0.dist-info/licenses/LICENSE,sha256=wmvw04AdbaH7ybiJEgRhD3Mjxm55CWkapYjM-3SMqKA,1080
|
|
16
|
+
riskengine_var-1.0.0.dist-info/METADATA,sha256=8Kn_2dDOjKzv0vxkaOMp8giNSwq5visQPM12Nam82Tg,385
|
|
17
|
+
riskengine_var-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
18
|
+
riskengine_var-1.0.0.dist-info/entry_points.txt,sha256=BmofoaEUESZgXuMF8kXKAAoedu1HjgcLNAzZF0atFsg,51
|
|
19
|
+
riskengine_var-1.0.0.dist-info/top_level.txt,sha256=05cQXl6v-U9AEJedqKsGfVC6E3ZVLwABjM47vm7S5Pc,11
|
|
20
|
+
riskengine_var-1.0.0.dist-info/RECORD,,
|
|
@@ -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 @@
|
|
|
1
|
+
riskengine
|