GRS*_*GRS 1 python numpy pandas
我定义的价格动量是过去n天给定股票动量的平均值.
反过来,动量是一种分类:如果当天的收盘价高于前一天,则每天标记为1;如果价格低于前一天,则标记为-1.
我的库存变化百分比如下:
df['close in percent'] = np.array([0.27772152, 1.05468772,
0.124156 , -0.39298394,
0.56415267, 1.67812005])
momentum = df['close in percent'].apply(lambda x: 1 if x > 0 else -1).values
Run Code Online (Sandbox Code Playgroud)
Momentum应该是:[1,1,1,-1,1,1].
因此,如果我发现过去n = 3天的平均动量,我希望我的价格势头为:
Price_momentum = [Nan, Nan, 1, 1/3, 1/3, 1/3]
Run Code Online (Sandbox Code Playgroud)
我设法使用以下代码使其工作,但这非常慢(数据集是5000多行,执行需要10分钟).
for i in range(3,len(df)+1,1):
data = np.array(momentum[i-3:i])
df['3_day_momentum'].iloc[i-1]=data.mean()
Run Code Online (Sandbox Code Playgroud)
您可以创建一个rolling对象:
df = pd.DataFrame()
df['close_in_percent'] = np.array([0.27772152, 1.05468772,
0.124156 , -0.39298394,
0.56415267, 1.67812005])
df['momentum'] = np.where(df['close_in_percent'] > 0, 1, -1)
df['3_day_momentum'] = df.momentum.rolling(3).mean()
Run Code Online (Sandbox Code Playgroud)
在这里,它np.where是一种替代方案apply(),通常很慢,应该作为最后的手段.
close_in_percent momentum 3_day_momentum
0 0.2777 1 NaN
1 1.0547 1 NaN
2 0.1242 1 1.0000
3 -0.3930 -1 0.3333
4 0.5642 1 0.3333
5 1.6781 1 0.3333
Run Code Online (Sandbox Code Playgroud)
你可以用np.where+ pd.Rolling.mean-
s = df['close in percent']
pd.Series(np.where(s > 0, 1, -1)).rolling(3).mean()
0 NaN
1 NaN
2 1.000000
3 0.333333
4 0.333333
5 0.333333
dtype: float64
Run Code Online (Sandbox Code Playgroud)
对于v0.17或更低版本,还rolling_mean可以直接使用数组.
pd.rolling_mean(np.where(s > 0, 1, -1), window=3)
array([ nan, nan, 1. , 0.33333333, 0.33333333,
0.33333333])
Run Code Online (Sandbox Code Playgroud)