# Chapter 44: Financial Risk Management
# Fundamentals of Python for Financial Econometrics - Financial Risk Management
# Dataset: Ceteris Lab teaching sample

# Financial Risk Management
#
# **Opening question:** How much could be lost, how often should that threshold be exceeded, and what happens beyond it?

# %% Cell 2
import numpy as np

rng = np.random.default_rng(25)
returns = 0.01 * rng.standard_t(df=5, size=2_000)
losses = -returns
q = 0.99
var = np.quantile(losses, q)
es = losses[losses >= var].mean()
print(round(var, 4), round(es, 4), int((losses >= var).sum()))

# **Interpretation check:** Interpretation. At the 99th percentile, roughly 20 of 2,000 simulated observations lie in the tail used for ES, illustrating tail-sample scarcity.

# %% Cell 4
threshold = np.full_like(losses, var)
exceed = losses > threshold
expected = len(losses) * (1-q)
print(exceed.sum(), round(expected, 1), round(exceed.mean(), 4))

# **Interpretation check:** Interpretation. The unconditional exceedance rate matches by construction for an in-sample historical quantile. A real backtest must forecast each threshold using only prior information.

# %% Cell 6
import numpy as np
rng = np.random.default_rng(25)
returns = 0.01 * rng.standard_t(df=5, size=2_000)
var = np.quantile(losses, q)
es = losses[losses >= var].mean()
print(round(var, 4), round(es, 4), int((losses >= var).sum()))

# Verified source output
#
# ```text
# 0.0383 0.0518 20
# ```
#
# ```text
# 20 20.0 0.01
# ```
