我有一个数据集:
Open High Low Close
0 132.960 133.340 132.940 133.105
1 133.110 133.255 132.710 132.755
2 132.755 132.985 132.640 132.735
3 132.730 132.790 132.575 132.685
4 132.685 132.785 132.625 132.755
Run Code Online (Sandbox Code Playgroud)
我尝试对所有行使用rolling.apply函数,如下所示:
df['new_col']= df[['Open']].rolling(2).apply(AccumulativeSwingIndex(df['High'],df['Low'],df['Close']))
Run Code Online (Sandbox Code Playgroud)
要么
df['new_col']= df[['Open', 'High', 'Low', 'Close']].rolling(2).apply(AccumulativeSwingIndex)
Run Code Online (Sandbox Code Playgroud)
有谁能够帮我?
继续这个问题Python自定义函数使用rolling_apply进行pandas,关于使用rolling_apply.虽然我已经使用了我的函数,但我正在努力处理需要两列或更多列作为输入的函数:
创建与以前相同的设置
import pandas as pd
import numpy as np
import random
tmp = pd.DataFrame(np.random.randn(2000,2)/10000,
index=pd.date_range('2001-01-01',periods=2000),
columns=['A','B'])
Run Code Online (Sandbox Code Playgroud)
但稍微改变功能需要两列.
def gm(df,p):
df = pd.DataFrame(df)
v =((((df['A']+df['B'])+1).cumprod())-1)*p
return v.iloc[-1]
Run Code Online (Sandbox Code Playgroud)
它会产生以下错误:
pd.rolling_apply(tmp,50,lambda x: gm(x,5))
KeyError: u'no item named A'
Run Code Online (Sandbox Code Playgroud)
我认为这是因为lambda函数的输入是长度为50且仅在第一列的ndarray,并且不会将两列作为输入.有没有办法将两列作为输入并在rolling_apply函数中使用它.
再次感谢任何帮助......
我有很多(4000+)CSV的库存数据(日期,开放,高,低,关闭),我将其导入单个Pandas数据帧以执行分析.我是python的新手,想要计算每个股票的滚动12个月测试版,我找到了一个计算滚动测试版的帖子(Python pandas使用滚动应用于矢量化方式的groupby对象来计算车辆股票beta)但是当我在下面的代码中使用时需要超过2.5小时!考虑到我可以在3分钟内在SQL表中运行完全相同的计算,这太慢了.
如何提高下面的代码的性能以匹配SQL的性能?我理解Pandas/python有这种能力.我当前的方法遍历每一行,我知道这会降低性能,但我不知道在数据帧上执行滚动窗口beta计算的任何聚合方式.
注意:将CSV加载到单个数据帧并计算每日返回的前两个步骤仅需约20秒.我的所有CSV数据帧都存储在名为"FilesLoaded"的字典中,其名称为"XAO".
非常感谢您的帮助!谢谢 :)
import pandas as pd, numpy as np
import datetime
import ntpath
pd.set_option('precision',10) #Set the Decimal Point precision to DISPLAY
start_time=datetime.datetime.now()
MarketIndex = 'XAO'
period = 250
MinBetaPeriod = period
# ***********************************************************************************************
# CALC RETURNS
# ***********************************************************************************************
for File in FilesLoaded:
FilesLoaded[File]['Return'] = FilesLoaded[File]['Close'].pct_change()
# ***********************************************************************************************
# CALC BETA
# ***********************************************************************************************
def calc_beta(df):
np_array = df.values
m = np_array[:,0] # market returns are column zero from numpy array
s = np_array[:,1] # stock …Run Code Online (Sandbox Code Playgroud) 我正在尝试以滚动方式计算交易量加权平均价格.
要做到这一点,我有一个函数vwap为我这样做,像这样:
def vwap(bars):
return ((bars.Close*bars.Volume).sum()/bars.Volume.sum()).round(2)
Run Code Online (Sandbox Code Playgroud)
当我尝试将此函数与rolling_apply一起使用时,如图所示,我收到一个错误:
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'
Run Code Online (Sandbox Code Playgroud)
这个错误对我有意义,因为rolling_apply不需要DataSeries或ndarray作为输入而不是dataFrame ..我正在这样做.
有没有办法使用rolling_apply到DataFrame来解决我的问题?
我想使用该pandas.rolling_apply函数在滚动窗口的基础上应用我自己的自定义函数.
但是我的函数需要两个参数,并且还有两个输出.这可能吗?
以下是一个可重复的最小例子......
import pandas as pd
import numpy as np
import random
tmp = pd.DataFrame(np.random.randn(2000,2)/10000,
index=pd.date_range('2001-01-01',periods=2000),
columns=['A','B'])
def gm(df,p):
v =(((df+1).cumprod())-1)*p
return v.iloc[-1]
# an example output when subsetting for just 2001
gm(tmp['2001'],5)
# the aim is to do it on a rolling basis over a 50 day window
# whilst also getting both outputs and also allows me to add in the parameter p=5
# or any other number I want p to be...
pd.rolling_apply(tmp,50,gm)
Run Code Online (Sandbox Code Playgroud)
导致错误...因为gm有两个参数...... …
我想要一个滚动窗口的数据帧表示.我没有在滚动窗口上执行某些操作,而是想要一个数据框,其中窗口在另一个维度中表示.这可能是一个pd.Panel或np.array或pd.DataFrame用pd.MultiIndex.
import pandas as pd
import numpy as np
np.random.seed([3,1415])
df = pd.DataFrame(np.random.rand(10, 3).round(2),
columns=['A', 'B', 'C'],
index=list('abcdefghij'))
print df
A B C
a 0.44 0.41 0.46
b 0.47 0.46 0.02
c 0.85 0.82 0.78
d 0.76 0.93 0.83
e 0.88 0.93 0.72
f 0.12 0.15 0.20
g 0.44 0.10 0.28
h 0.61 0.09 0.84
i 0.74 0.87 0.69
j 0.38 0.23 0.44
Run Code Online (Sandbox Code Playgroud)
对于window = 2我希望结果是.
0 1 …Run Code Online (Sandbox Code Playgroud)