Skip to content

Instantly share code, notes, and snippets.

@kavehtehrani
Last active December 4, 2025 04:20
Show Gist options
  • Select an option

  • Save kavehtehrani/ae4768d8d00b9c477b582b8c124f26ad to your computer and use it in GitHub Desktop.

Select an option

Save kavehtehrani/ae4768d8d00b9c477b582b8c124f26ad to your computer and use it in GitHub Desktop.
var vs cvar - coherence of risk measures
import numpy as np
import pandas as pd
A = np.array([1.0] * 18 + [-100.0, 0.0, -30.0])
B = np.array([1.0] * 18 + [0.0, -100.0, -30.0])
P = 0.5 * A + 0.5 * B
def var(r, alpha=0.90):
return np.percentile(r, 100 * (1 - alpha))
def cvar(r, alpha=0.90):
v = var(r, alpha)
return r[r <= v].mean()
tgt_threshold = 0.9
out = pd.DataFrame({
"A": [var(A, tgt_threshold), cvar(A, tgt_threshold)],
"B": [var(B, tgt_threshold), cvar(B, tgt_threshold)],
"Portfolio": [var(P, tgt_threshold), cvar(P, tgt_threshold)]
}, index=["VaR", "CVaR"])
corr_AB = np.corrcoef(A, B)[0, 1]
out = out.astype(float).map(lambda x: f"{x:,.2f}")
print(out)
print(f"\nCorrelation between A and B: {corr_AB:.2f}")
### OUTPUT ###
# A B Portfolio
# VaR -0.00 -0.00 -30.00
# CVaR -65.00 -65.00 -50.00
#
# Correlation between A and B: 0.03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment