EWMA Volatility in Python - Avoiding loops

喜夏-厌秋 提交于 2020-05-13 06:57:04

问题


I have a time series that looks like this (a slice):

Date         3         7           10
2015-02-13   0.00021  -0.00078927  0.00407473
2015-02-16   0.0      -0.00343163  0.0
2015-02-17   0.0       0.0049406   0.00159753
2015-02-18   0.00117  -0.00123565 -0.00031423
2015-02-19   0.00091  -0.00253578 -0.00106207
2015-02-20   0.00086   0.00113476  0.00612649
2015-02-23  -0.0011   -0.00403307 -0.00030327
2015-02-24  -0.00179   0.00043229  0.00275874
2015-02-25   0.00035   0.00186069 -0.00076578
2015-02-26  -0.00032  -0.01435613 -0.00147597
2015-02-27  -0.00288  -0.0001786  -0.00295631

For calculating the EWMA Volatility, I implemented the following functions:

def CalculateEWMAVol (ReturnSeries, Lambda):   
    SampleSize = len(ReturnSeries)
    Average = ReturnSeries.mean()

    e = np.arange(SampleSize-1,-1,-1)
    r = np.repeat(Lambda,SampleSize)
    vecLambda = np.power(r,e)

    sxxewm = (np.power(ReturnSeries-Average,2)*vecLambda).sum()
    Vart = sxxewm/vecLambda.sum()
    EWMAVol = math.sqrt(Vart)

    return (EWMAVol)

def CalculateVol (R, Lambda):
    Vol = pd.Series(index=R.columns)
    for facId in R.columns:
        Vol[facId] = CalculateEWMAVol(R[facId], Lambda)

    return (Vol)

The function works properly, but with a large time series the process gets slow because of the for loop.

Is there another approach to calling this function over the series?


回答1:


I think your function to be the most technically right approach. I just wanted to suggest to use 'apply', instead of doing a 'for' yourself.

Is there another approach to calling this function over the series?

Vol[facId] = R.apply(CalculateEWMAVol(R[facId], Lambda)

I hope it can be useful.




回答2:


I guess what you really asked is to avoid using loop, but the pandas apply() does not solve this problem, because you still loop around each column in your dataframe. I explored this topic a while ago, after exhausting my options, I end up converting a MatLab matrix calculation to Python code and it does the vol with decay calculation perfectly in matrix form. Code in the following, assuming df_tmp is the time series that has multiple columns for each price index.

decay_factor = 0.94
decay_f = np.arange(df_tmp.shape[0], 0, -1)
decay_f = decay_factor ** decay_f
decay_sum = sum(decay_f)
w = decay_f / decay_sum
avg_weight = np.ones(df_tmp.shape[0]) / df_tmp.shape[0]
T, N = df_tmp.shape
temp = df_tmp - df_tmp * np.tile(avg_weight, (4422, 1)).T
temp = np.dot(temp.T, temp * np.tile(w, (4422, 1)).T)
temp = 0.5 * (temp + temp.T)
R = np.diag(temp)
sigma = np.sqrt(R)
R = temp / np.sqrt(np.dot(R, R.T))

sigma is volatility, R is corr matrix and temp is covariance matrix.



来源:https://stackoverflow.com/questions/42305587/ewma-volatility-in-python-avoiding-loops

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!