financial.expected_shortfall ============================ .. py:module:: financial.expected_shortfall .. autoapi-nested-parse:: Expected Shortfall (ES), also known as Conditional Value at Risk (CVaR), estimated with historical simulation. References: - https://en.wikipedia.org/wiki/Expected_shortfall - https://www.investopedia.com/terms/c/conditional_value_at_risk.asp Expected Shortfall measures the average loss that occurs in the tail of the loss distribution beyond the Value at Risk threshold. Unlike Value at Risk, which only reports a quantile boundary, Expected Shortfall captures how bad the losses actually are when the worst cases happen, and it is a coherent risk measure. Functions --------- .. autoapisummary:: financial.expected_shortfall._linear_interpolated_quantile financial.expected_shortfall.expected_shortfall Module Contents --------------- .. py:function:: _linear_interpolated_quantile(sorted_values: collections.abc.Sequence[float], quantile: float) -> float Linear interpolation between the closest ranks (NumPy default, type 7). >>> _linear_interpolated_quantile([-10.0, -5.0, -2.0, 1.0, 4.0], 0.25) -5.0 .. py:function:: expected_shortfall(returns: collections.abc.Sequence[float], confidence_level: float = 0.95) -> float Calculate the historical-simulation Expected Shortfall of a portfolio. The confidence level is the probability that the loss will not exceed the corresponding Value at Risk threshold. The tail contains every observed return at or below that threshold, and the result is the negative of the average of that tail, i.e. a positive loss magnitude when the tail contains losses. Examples: >>> expected_shortfall([-10, -5, -2, 1, 4], 0.95) 10.0 >>> expected_shortfall([-10, -5, -2, 1, 4], 0.75) 7.5 >>> expected_shortfall([], 0.95) Traceback (most recent call last): ... ValueError: returns must not be empty >>> expected_shortfall([-1, 0, 1], 0.0) Traceback (most recent call last): ... ValueError: confidence_level must be strictly between 0 and 1 >>> expected_shortfall([-1, float("inf"), 1], 0.95) Traceback (most recent call last): ... ValueError: returns must contain only finite numbers Time complexity: O(n log n), where n = len(returns), for sorting. Space complexity: O(n) for the sorted copy and the tail.