pythonrisk-analysis

Storing data with Python arrays (HAR-RV Credit Risk model implementation)


I'm dealing with the HAR-RV model, trying to run this equation but having no success at all to store my operations on the array

Here what I'm trying to calculate:

r_[t,i] = Y_[t,i] - Y_[t,i-1] 

https://cdn1.imggmi.com/uploads/2019/8/30/299a4ab026de7db33c4222b30f3ed70a-full.png

Im using the first relation here, where r means return and Y the stock prices

t = 10 # daily intervals

i = 30 # number of days

s = 1

# (Here I've just created some fake numbers, intending to simulate some stock prices)

Y = abs(np.random.random((10,30)) + 1)  

# initializing my return array
return = np.array([])

# (I also tried to initialize it as a Matrix before..) : 
return = np.zeros((10,30))

# here is my for loop to store each daily return at its position on the "return" Array. I wanted an Array  but got just "() size"
 
for t in range(0,9):    
    for i in range(1,29):                                  
        return = np.array( Y.item((t,i)) - Y.item((t,i-1)) )

... so, I was expecting something like this:

return = [first difference, second difference, third difference...]

how can I do that ?


Solution

  • first don't use return as a variable name in python as it is a python keyword (it signifies the result of a function). I have changed your variable return to ret_val.

    You are wanting to make a change at each position in your array, so make the following change to your for loop:

    for t in range(0,10):
        for i in range(1,30):
            ret_val[t][i] = Y[t][i] - Y[t][i-1]
    print(ret_val)
    

    This is saying to change the value at index ret_val[t][i] with the result of subtracting the values at that specific index in Y. You should see an array of the same shape when you print.

    Also, the range function in python does not include the upper number. So when you say, for i in range(0,9) you are saying to include numbers 0-8. For your array, you'll want to do for i in range(0,10) to include all values in your array. Correspondingly, you'll want to do the same for i in range(1,30).