[英]How to calculate vwap (volume weighted average price) using groupby and apply?
我已經閱讀了多篇類似於我的問題的帖子,但我仍然無法弄清楚。 我有一個如下所示的 Pandas df(多天):
Out[1]:
price quantity
time
2016-06-08 09:00:22 32.30 1960.0
2016-06-08 09:00:22 32.30 142.0
2016-06-08 09:00:22 32.30 3857.0
2016-06-08 09:00:22 32.30 1000.0
2016-06-08 09:00:22 32.35 991.0
2016-06-08 09:00:22 32.30 447.0
...
要計算 vwap,我可以這樣做:
df['vwap'] = (np.cumsum(df.quantity * df.price) / np.cumsum(df.quantity))
但是,我想每天重新開始(groupby),但我不知道如何使其與(lambda?)函數一起工作。
df['vwap_day'] = df.groupby(df.index.date)['vwap'].apply(lambda ...
速度至關重要。 將不勝感激任何幫助:)
選項 0
純香草方法
def vwap(df):
q = df.quantity.values
p = df.price.values
return df.assign(vwap=(p * q).cumsum() / q.cumsum())
df = df.groupby(df.index.date, group_keys=False).apply(vwap)
df
price quantity vwap
time
2016-06-08 09:00:22 32.30 1960.0 32.300000
2016-06-08 09:00:22 32.30 142.0 32.300000
2016-06-08 09:00:22 32.30 3857.0 32.300000
2016-06-08 09:00:22 32.30 1000.0 32.300000
2016-06-08 09:00:22 32.35 991.0 32.306233
2016-06-08 09:00:22 32.30 447.0 32.305901
選項 1
投入一點eval
df = df.assign(
vwap=df.eval(
'wgtd = price * quantity', inplace=False
).groupby(df.index.date).cumsum().eval('wgtd / quantity')
)
df
price quantity vwap
time
2016-06-08 09:00:22 32.30 1960.0 32.300000
2016-06-08 09:00:22 32.30 142.0 32.300000
2016-06-08 09:00:22 32.30 3857.0 32.300000
2016-06-08 09:00:22 32.30 1000.0 32.300000
2016-06-08 09:00:22 32.35 991.0 32.306233
2016-06-08 09:00:22 32.30 447.0 32.305901
我之前也使用過這種方法,但如果您試圖限制窗口期,它的效果就不太准確。 相反,我發現 TA python 庫工作得非常好: https : //technical-analysis-library-in-python.readthedocs.io/en/latest/index.html
from ta.volume import VolumeWeightedAveragePrice
# ...
def vwap(dataframe, label='vwap', window=3, fillna=True):
dataframe[label] = VolumeWeightedAveragePrice(high=dataframe['high'], low=dataframe['low'], close=dataframe["close"], volume=dataframe['volume'], window=window, fillna=fillna).volume_weighted_average_price()
return dataframe
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.