gpt4 book ai didi

python - Python 中的 EWMA 波动性——避免循环

转载 作者:行者123 更新时间:2023-11-28 19:09:26 27 4
gpt4 key购买 nike

我有一个看起来像这样的时间序列(切片):

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 循环,该过程会变慢。

是否有另一种方法可以通过系列调用此函数?

最佳答案

我猜你真正想问的是避免使用循环,但 pandas apply() 并没有解决这个问题,因为你仍然在你的数据框中循环每一列。不久前我探讨了这个主题,在用尽了我的选择之后,我最终将 MatLab 矩阵计算转换为 Python 代码,它以矩阵形式完美地进行了 vol with decay 计算。以下代码,假设 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 是相关矩阵,temp 是协方差矩阵。

关于python - Python 中的 EWMA 波动性——避免循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42305587/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com