在DataFrame对象上使用rolling_apply [英] Using rolling_apply on a DataFrame object

查看:1243
本文介绍了在DataFrame对象上使用rolling_apply的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以滚动方式计算交易量加权平均价格.

I am trying to calculate Volume Weighted Average Price on a rolling basis.

要做到这一点,我有一个函数vwap可以为我做到这一点,就像这样:

To do this, I have a function vwap that does this for me, like so:

def vwap(bars):
    return ((bars.Close*bars.Volume).sum()/bars.Volume.sum()).round(2)

如图所示,当我尝试将此函数与rolling_apply一起使用时,出现错误:

When I try to use this function with rolling_apply, as shown, I get an error:

import pandas.io.data as web
bars = web.DataReader('AAPL','yahoo')
print pandas.rolling_apply(bars,30,vwap)

AttributeError: 'numpy.ndarray' object has no attribute 'Close'

该错误对我来说很有意义,因为rolling_apply不需要DataSeries或ndarray作为输入,也不需要dataFrame ..按我的方式做.

The error makes sense to me because the rolling_apply requires not DataSeries or a ndarray as an input and not a dataFrame.. the way I am doing it.

有没有一种方法可以将rolling_apply应用于DataFrame来解决我的问题?

Is there a way to use rolling_apply to a DataFrame to solve my problem?

推荐答案

此功能未直接启用,但您可以这样做

This is not directly enabled, but you can do it like this

In [29]: bars
Out[29]: 
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 942 entries, 2010-01-04 00:00:00 to 2013-09-30 00:00:00
Data columns (total 6 columns):
Open         942  non-null values
High         942  non-null values
Low          942  non-null values
Close        942  non-null values
Volume       942  non-null values
Adj Close    942  non-null values
dtypes: float64(5), int64(1)

window=30

In [30]: concat([ (Series(vwap(bars.iloc[i:i+window]),
                      index=[bars.index[i+window]])) for i in xrange(len(df)-window) ])
Out[30]: 
2010-02-17    203.21
2010-02-18    202.95
2010-02-19    202.64
2010-02-22    202.41
2010-02-23    202.19
2010-02-24    201.85
2010-02-25    201.65
2010-02-26    201.50
2010-03-01    201.31
2010-03-02    201.35
2010-03-03    201.42
2010-03-04    201.09
2010-03-05    200.95
2010-03-08    201.50
2010-03-09    202.02
...
2013-09-10    485.94
2013-09-11    487.38
2013-09-12    486.77
2013-09-13    487.23
2013-09-16    487.20
2013-09-17    486.09
2013-09-18    485.52
2013-09-19    485.30
2013-09-20    485.37
2013-09-23    484.87
2013-09-24    485.81
2013-09-25    486.41
2013-09-26    486.07
2013-09-27    485.30
2013-09-30    484.74
Length: 912

这篇关于在DataFrame对象上使用rolling_apply的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆