fincore.risk¶
Walk-forward validation report¶
fincore.risk.report
¶
Portable audit reports for the enhanced walk-forward VaR boundary.
The report intentionally represents only the validated one-step, lower-tail
VaR path produced by :func:fincore.risk.walk_forward_var. It records every
out-of-sample forecast/realisation pair, exception, refit and input digest in
a deterministic JSON artifact. It is a Basel-oriented reference aid, not a
regulatory approval or compliance certification.
RiskValidationReport(status, inputs_digest, specification, forecast_events, refits, diagnostics, backtest, timestamp_index_name=None, timestamp_timezone=None, disclosure=BASEL_REFERENCE_DISCLOSURE, schema_version=RISK_VALIDATION_REPORT_SCHEMA_VERSION)
dataclass
¶
A JSON-serializable audit record for one walk-forward VaR result.
forecast_events has one record for every out-of-sample timestamp. A
record includes the forecast, realised return, exception flag and whether
the model was refitted at that timestamp. refits holds the fitted
parameters recorded by the underlying walk-forward run. Along with the
input and backtest digests, this is sufficient to reconstruct the
validation evidence without exposing the in-sample return history.
__post_init__()
¶
Freeze all nested JSON values after validating their shape.
to_dict()
¶
Return a detached JSON-compatible representation of this report.
to_json()
¶
Serialize the report as deterministic, human-readable JSON.
write_json(path)
¶
Write the deterministic JSON artifact to path and return it.
The caller owns directory creation and output-retention policy. This method deliberately does not create missing parent directories.
build_risk_validation_report(result)
¶
Create an auditable report from a validated walk-forward VaR result.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
result
|
WalkForwardVaRResult
|
A :class: |
必需 |
返回:
| 类型 | 描述 |
|---|---|
RiskValidationReport
|
A portable record of forecast timestamps, exceptions, refits, model
parameters, inputs digest, and backtest statistics. An
|
Notes
The Basel traffic-light fields are a reference implementation. This function does not certify a regulatory model, approve capital treatment, or extend validation to legacy GARCH/EVT APIs.
EVT (Extreme Value Theory)¶
fincore.risk.evt
¶
Extreme Value Theory (EVT) models for tail risk estimation.
EVT provides better estimates of extreme losses than normal distribution assumptions, particularly for:
- Tail index estimation (Hill estimator)
- Peaks-over-threshold (POT) with Generalized Pareto Distribution (GPD)
- Block maxima with Generalized Extreme Value (GEV) distribution
References
Embrechts, P., Klüppelberg, C., & Mikosch, T. (1997). Modelling Extremal Events for Insurance and Finance. McNeil, A. J., Frey, R., & Embrechts, P. (2015). Quantitative Risk Management.
hill_estimator(data, threshold=None, tail='upper')
¶
Estimate tail index using Hill estimator.
The Hill estimator is a popular method for estimating the tail index (extreme value index) of heavy-tailed distributions.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
data
|
array - like
|
Input data (returns or losses). |
必需 |
threshold
|
float
|
Positive tail-magnitude threshold. If None, uses the 90th percentile of the selected positive tail magnitudes. |
None
|
tail
|
str
|
Which tail to estimate: 'upper' (right/gains) or 'lower' (left/losses). |
'upper'
|
返回:
| 名称 | 类型 | 描述 |
|---|---|---|
xi |
float
|
Estimated tail index (shape parameter). The Hill estimator is defined for regularly varying heavy tails, so finite-sample estimates are non-negative. Values close to zero can indicate a light/near-exponential tail; use a GPD/GEV model rather than Hill for a bounded-tail (negative-shape) conclusion. |
tail_observations |
ndarray
|
Positive tail magnitudes strictly above |
示例:
gpd_fit(data, threshold=None, method='mle', tail='lower')
¶
Fit Generalized Pareto Distribution (GPD) to exceedances.
GPD is used in Peaks-Over-Threshold (POT) method for modeling tail exceedances above a threshold.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
data
|
array - like
|
Input data (returns or losses). |
必需 |
threshold
|
float
|
Threshold for POT. If None, uses 90th percentile. |
None
|
method
|
str
|
Estimation method: 'mle' (maximum likelihood) or 'pwm' (probability weighted moments). |
'mle'
|
返回:
| 类型 | 描述 |
|---|---|
dict
|
Fitted parameters: - 'xi' (shape): Tail index - 'beta' (scale): Scale parameter - 'threshold': Fitted threshold - 'n_exceed': Number of exceedances |
示例:
gev_fit(data, block_size=None, tail='lower')
¶
Fit Generalized Extreme Value (GEV) distribution to block maxima.
GEV is used for modeling maximum values over fixed time blocks (e.g., monthly maximum losses).
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
data
|
array - like
|
Input data (returns or losses). |
必需 |
block_size
|
int
|
Size of each block for extracting maxima. If None, uses sqrt(n) blocks. |
None
|
返回:
| 类型 | 描述 |
|---|---|
dict
|
Fitted parameters: - 'xi' (shape): Tail index - 'mu' (location): Location parameter - 'sigma' (scale): Scale parameter |
示例:
evt_var(data, alpha=0.05, model='gpd', tail='lower', threshold=None, block_size=None)
¶
Calculate VaR using Extreme Value Theory.
EVT-based VaR provides better tail risk estimates than normal distribution assumptions.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
data
|
array - like
|
Input return data. |
必需 |
alpha
|
float
|
Finite tail probability in |
0.05
|
model
|
str
|
EVT model: 'gpd' (POT) or 'gev' (block maxima). |
'gpd'
|
tail
|
str
|
Tail to estimate: 'lower' for losses, 'upper' for gains. |
'lower'
|
threshold
|
float
|
Threshold for GPD fitting. An explicit threshold must leave an
empirical exceedance probability at least |
None
|
block_size
|
int
|
Block size for GEV fitting. |
None
|
返回:
| 类型 | 描述 |
|---|---|
float
|
EVT-based VaR estimate (negative value for losses). |
示例:
evt_cvar(data, alpha=0.05, model='gpd', tail='lower', threshold=None, block_size=None)
¶
Calculate CVaR (Expected Shortfall) using EVT.
EVT-based CVaR provides better average tail loss estimates.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
data
|
array - like
|
Input return data. |
必需 |
alpha
|
float
|
Finite tail probability in |
0.05
|
model
|
str
|
EVT model: 'gpd' or 'gev'. |
'gpd'
|
tail
|
str
|
Tail to estimate. |
'lower'
|
threshold
|
float
|
GPD threshold with the same domain requirement and automatic policy as
:func: |
None
|
block_size
|
int
|
Block size for GEV fitting. |
None
|
返回:
| 类型 | 描述 |
|---|---|
float
|
EVT-based conditional tail mean (negative value for losses). GEV ES is
finite only for |
示例:
extreme_risk(returns, alpha=0.05, tail='lower', model='gpd', threshold=None, block_size=None)
¶
Calculate comprehensive EVT-based risk measures.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
returns
|
Series
|
Return series. |
必需 |
alpha
|
float
|
Significance level. |
0.05
|
tail
|
str
|
Tail to estimate. |
'lower'
|
model
|
str
|
EVT model. |
'gpd'
|
threshold
|
float
|
Threshold for GPD fitting. |
None
|
block_size
|
int
|
Block size for GEV fitting. |
None
|
返回:
| 类型 | 描述 |
|---|---|
DataFrame
|
Risk measures including VaR, CVaR, tail index, and threshold. |
示例:
GARCH¶
fincore.risk.garch
¶
GARCH models for conditional volatility estimation.
Provides GARCH family models for time-varying volatility estimation: - GARCH(p, q): Generalized Autoregressive Conditional Heteroskedasticity - EGARCH: Exponential GARCH (asymmetric effects) - GJR-GARCH: Glosten-Jagannathan-Runkle GARCH (leverage effect)
References
Engle, R. F. (1982). Autoregressive Conditional Heteroscedasticity. Bollerslev, T. (1986). Generalized Autoregressive Conditional Heteroscedasticity. Nelson, D. B. (1991). Conditional Heteroskedasticity in Asset Returns. Glosten, L. R., Jagannathan, R., & Runkle, D. E. (1993). On the Relation Between the Expected Value and the Volatility of the Nominal Excess Return on Stocks.
GARCHResult(params, conditional_var, residuals, log_likelihood, model_type='garch', converged=True)
dataclass
¶
Result of GARCH model fitting.
属性:
| 名称 | 类型 | 描述 |
|---|---|---|
params |
dict
|
Fitted parameters (omega, alpha, beta, etc.). |
conditional_var |
ndarray
|
Fitted conditional variances. |
residuals |
ndarray
|
Standardized residuals. |
log_likelihood |
float
|
Maximized log-likelihood value. |
model_type |
str
|
One of |
converged |
bool
|
Whether the optimizer reported success and the fitted parameters pass the finite/stationarity checks for the selected GARCH family. |
forecast(horizon=1)
¶
Forecast future conditional variances.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
horizon
|
int
|
Number of steps ahead to forecast. |
1
|
返回:
| 类型 | 描述 |
|---|---|
ndarray
|
Forecasted variances. |
GARCH(p=1, q=1, mean_model='zero')
¶
GARCH(p, q) model for conditional volatility.
The standard GARCH(p, q) model: sigma_t^2 = omega + sum(alpha_i * epsilon_{t-i}^2) + sum(beta_j * sigma_{t-j}^2)
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
p
|
int
|
Order of ARCH terms (past squared shocks). |
1
|
q
|
int
|
Order of GARCH terms (past conditional variances). |
1
|
mean_model
|
str
|
Mean model: 'zero' (zero mean), 'constant' (constant mean). |
'zero'
|
示例:
>>> returns = pd.Series(np.random.randn(1000) * 0.02)
>>> model = GARCH(p=1, q=1)
>>> result = model.fit(returns)
>>> forecasts = result.forecast(horizon=10)
fit(returns, method='MLE')
¶
Fit GARCH model to returns.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
returns
|
Series or ndarray
|
Return series (not prices!). |
必需 |
method
|
str
|
Estimation method: 'MLE' (max likelihood) or 'OLS'. |
'MLE'
|
返回:
| 类型 | 描述 |
|---|---|
GARCHResult
|
Fitted model result. |
EGARCH(p=1, q=1)
¶
Exponential GARCH model for asymmetric volatility.
EGARCH models the log of variance, allowing for: - Leverage effects (negative shocks have different impact) - Guaranteed positive variance
The EGARCH(1,1) model: log(sigma_t^2) = omega + alpha * |z_{t-1}| + gamma * z_{t-1} + beta * log(sigma_{t-1}^2)
where z_t = epsilon_t / sigma_t are standardized shocks.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
p
|
int
|
Order of asymmetric terms. |
1
|
q
|
int
|
Order of GARCH terms. |
1
|
示例:
>>> returns = pd.Series(np.random.randn(1000) * 0.02)
>>> model = EGARCH()
>>> result = model.fit(returns)
>>> forecasts = result.forecast(horizon=10)
fit(returns)
¶
Fit EGARCH model to returns.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
returns
|
Series or ndarray
|
Return series with at least ten finite observations and strictly positive finite sample variance. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
GARCHResult
|
Fitted model result. |
GJRGARCH(p=1, q=1)
¶
GJR-GARCH model with leverage effect.
GJR-GARCH adds a term to capture asymmetric response to shocks: - Negative shocks (bad news) increase volatility more than positive shocks
The GJR-GARCH(1,1) model: sigma_t^2 = omega + alpha * epsilon_{t-1}^2 + gamma * I_{t-1} * epsilon_{t-1}^2 + beta * sigma_{t-1}^2
where I_t = 1 if epsilon_t < 0 else 0.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
p
|
int
|
Order of ARCH terms. |
1
|
q
|
int
|
Order of GARCH terms. |
1
|
示例:
>>> returns = pd.Series(np.random.randn(1000) * 0.02)
>>> model = GJRGARCH()
>>> result = model.fit(returns)
>>> print(f"Leverage gamma: {result.params['gamma']:.3f}")
fit(returns)
¶
Fit GJR-GARCH model to returns.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
returns
|
Series or ndarray
|
Return series. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
GARCHResult
|
Fitted model result including leverage parameter gamma. |
forecast_volatility(returns, model='GARCH', horizon=1, **kwargs)
¶
Forecast future volatility using GARCH models.
Convenience function for volatility forecasting.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
returns
|
Series or ndarray
|
Historical returns. |
必需 |
model
|
str
|
Model type: 'GARCH', 'EGARCH', 'GJRGARCH'. |
'GARCH'
|
horizon
|
int
|
Forecast horizon. |
1
|
**kwargs
|
Additional model parameters (p, q, etc.). |
{}
|
返回:
| 名称 | 类型 | 描述 |
|---|---|---|
forecasts |
ndarray
|
Forecasted conditional variances. |
result |
GARCHResult
|
Fitted model result. |
示例:
conditional_var(returns, model='GARCH', alpha=0.05, horizon=1, **kwargs)
¶
Calculate conditional VaR using GARCH models.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
returns
|
Series or ndarray
|
Historical returns. |
必需 |
model
|
str
|
Model type. |
'GARCH'
|
alpha
|
float
|
Significance level. |
0.05
|
horizon
|
int
|
Forecast horizon; multi-horizon VaR aggregates the forecast variances over the horizon (square-root-of-sum under independent increments). |
1
|
**kwargs
|
Additional model parameters. |
{}
|
返回:
| 类型 | 描述 |
|---|---|
dict
|
Contains 'var' (VaR estimate), 'cond_var' (forecast variances over the horizon), 'result' (full model fit) and 'converged' (optimizer status). |
conditional_es(returns, model='GARCH', alpha=0.05, horizon=1, **kwargs)
¶
Calculate conditional Expected Shortfall using GARCH models.
Under the normal-innovation assumption used by the GARCH family here, the
Expected Shortfall at tail probability alpha is::
ES = -sqrt(sigma^2) * phi(z_alpha) / alpha
which is strictly more extreme than the VaR z_alpha * sqrt(sigma^2).
sigma^2 is the horizon-aggregated forecast variance.
返回:
| 类型 | 描述 |
|---|---|
dict
|
Contains 'es', 'cond_var' (forecast variances), 'result' and 'converged'. |