Skip to content
Advertisement

Pandas: Apply rolling window on complex function (Hurst Exponent)

In a nutshell: I need to calculate the Hurst Exponent (HE) across a rolling window inside a pandas dataframe and assign the values to its own column.

The HE function I use was lifted from here as it seemed more robust. For convenience it’s posted below:

JavaScript

Now in order to test the function let’s grab some TSLA data from Yahoo finance:

JavaScript

Output:

JavaScript

So far so good. We have the function and the data to test it with. Now let’s do a sanity test, i.e. run the function against a subsample of the data:

JavaScript

Output:

JavaScript

Excellent.

Now to the meaty part. Applying the lambda across a rolling window and assigning the result to its own column. I’ve pretty much tried every trick I was able to dig up but cannot make it work.

The vanilla approach:

JavaScript

Gives me the following error:

JavaScript

Then I tried to get clever:

JavaScript

Also failed ignominiously. So at this point – half a day later – I’m pretty much stumped. Do any of you hardcore python aficionados know of a way to do this?

Thanks a lot in advance for any insights and pointers.

Advertisement

Answer

I think your problem is that your window is too short. It says in the docstring that the window length has to be 100+ elements, and the Hurst code isn’t handling it properly, resulting in a failure of the SVD.

Separately, your test is actually slicing everything but the last 20 elements, so is actually a long array, which is why it didn’t fail:

JavaScript

If you test a window < 100 length, it throws a LinAlg exception:

JavaScript

It should work if increase your rolling window length or repair the code in the Hurst function to pad out the array if it’s too short.

JavaScript

The code in the HurstEXP function for handling lists shorter than 100 elements won’t work for values of ts that are np.ndarray objects like those being provided from the .rolling(raw=True).

You could modify the function to start with the following, and it will work for windows under 100 elements:

JavaScript

…alternatively, if you’re always going to have numpy arrays, you could change the line that fixes it:

JavaScript

to

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement