簡體   English   中英

Python 中的 EWMA 波動性 - 避免循環

[英]EWMA Volatility in Python - Avoiding loops

我有一個看起來像這樣的時間序列(切片):

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

為了計算 EWMA 波動率,我實現了以下功能:

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)

該函數可以正常工作,但是對於大的時間序列,由於 for 循環,該過程會變慢。

是否有另一種方法可以通過系列調用此函數?

我認為您的功能是技術上最正確的方法。 我只是想建議使用“申請”,而不是“為”自己。

是否有另一種方法可以通過系列調用此函數?

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

我希望它有用。

我想您真正要求的是避免使用循環,但是 pandas apply() 並沒有解決這個問題,因為您仍然在數據框中的每一列周圍循環。 不久前我探索了這個主題,在用盡我的選擇之后,我最終將 MatLab 矩陣計算轉換為 Python 代碼,它以矩陣形式完美地完成了衰減計算的 vol。 下面的代碼,假設 df_tmp 是每個價格指數有多個列的時間序列。

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 是波動率,R 是 corr 矩陣,temp 是協方差矩陣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM