在熊猫数据框中计算收益的最佳方法是什么?

问题描述

我有一个如下的DataFrame

我要获取股票收益的标准偏差st.dev (T1/T0-1,T2/T1-1..etc)

例如st.dev((9.5/36.5)-1,(6.125/9.5)-1...etc)

结果将添加到2号数据帧中。

你能建议最好的方法吗?显然,我需要对所有股票执行此操作。你能帮忙吗?

预先感谢!

P.S:您可以忽略标准差部分,如果您可以帮助我提供退货,我会做剩下的事情。

enter image description here

enter image description here

解决方法

您可以使用df.pct_change获得config.vm.synced_folder值。从那里,您可以使用T1/T0-1聚合多个功能。

.agg

输出

# sample df
# please always provide a sample that can be easily pasted and tested
# you could get it with `df.head(10).to_dict('split')`
df = pd.DataFrame({
    'AAPL': [36.5,9.5,6.125,40.25,43.875,40,42.25],'TSL': [44,43.625,47.875,64.25,17.375,14.124,44.75],'GDXJ': [43.875,13.625,22.5,37.125,5.5,21.125,21.25],'DAL': [11.625,33.25,4.625,36,36.25,14.875,31.75]
})

df2 = df.pct_change().agg(['mean','std']).T
,

这就是我所需要的:

df.std(axis = 0,skipna = True) 
,

尝试一下:

a=[(df.iloc[i+1]/df.iloc[i])-1 for i in range(df.shape[0]-1)]
df1=pd.DataFrame(pd.DataFrame(a).std(),columns=["Return"])