Skip to content

Instantly share code, notes, and snippets.

@StuartGordonReid
Created June 12, 2015 11:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save StuartGordonReid/11f809725f1e717fffb6 to your computer and use it in GitHub Desktop.
Save StuartGordonReid/11f809725f1e717fffb6 to your computer and use it in GitHub Desktop.
Value at Risk Gist
import numpy
import numpy.random as nrand
"""
Note - for some of the metrics the absolute value is returns. This is because if the risk (loss) is higher we want to
discount the expected excess return from the portfolio by a higher amount. Therefore risk should be positive.
"""
def var(returns, alpha):
# This method calculates the historical simulation var of the returns
sorted_returns = numpy.sort(returns)
# Calculate the index associated with alpha
index = int(alpha * len(sorted_returns))
# VaR should be positive
return abs(sorted_returns[index])
def cvar(returns, alpha):
# This method calculates the condition VaR of the returns
sorted_returns = numpy.sort(returns)
# Calculate the index associated with alpha
index = int(alpha * len(sorted_returns))
# Calculate the total VaR beyond alpha
sum_var = sorted_returns[0]
for i in range(1, index):
sum_var += sorted_returns[i]
# Return the average VaR
# CVaR should be positive
return abs(sum_var / index)
# Example usage
r = nrand.uniform(-1, 1, 50)
print("VaR(0.05) =", var(r, 0.05))
print("CVaR(0.05) =", cvar(r, 0.05))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment