10.12.2019 Views

Python for Finance

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 11

VaR based on sorted historical returns

We know that stock returns do not necessarily follow a normal distribution. An

alternative is to use sorted returns to evaluate a VaR. This method is called VaR

based on historical returns. Assume that we have a daily return vector called ret. We

sort it from the smallest to the highest. Let's call the sorted return vector sorted_ret.

For a given confidence level, the one-period VaR is given here:

Here, position is our wealth (value of our portfolio), confidence is the confidence level and

n is the number of returns. The len() function shows the number of observations and

the int() function takes the integer part of an input value. For example, if the length of

the return vector is 200 and the confidence level is 99%, then the second value (200*0.01)

of the sorted returns, from the smallest to the highest, times our wealth, will be our VaR.

Obviously, if we have a longer time series, that is, more return observations, our final

VaR would be more accurate. For owning 500 shares of Walmart, what is the maximum

loss with a 99% confidence level the next day? First, let's look at several ways to sort our

data. The first one uses the numpy.sort() function:

import numpy as np

a = np.array([[1,-4],[9,10]])

b=np.sort(a)

print("a=",a)

print("b=",b)

('a=', array([[ 1, -4],

[ 9, 10]]))

('b=', array([[-4, 1],

[ 9, 10]]))

Here is the second way to sort by using Python's pandas module:

import pandas as pd

a = pd.DataFrame([[9,4],[9,2],[1,-1]],columns=['A','B'])

print(a)

# sort by A ascedning, then B descending

b= a.sort_values(['A', 'B'], ascending=[1, 0])

print(b)

# sort by A and B, both ascedning

c= a.sort_values(['A', 'B'], ascending=[1, 1])

print(c)

[ 405 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!