问题描述
我定义的价格动量是过去 n 天内给定股票动量的平均值.
I'm defining price momentum is an average of the given stock’s momentum over the past n days.
动量又是一个分类:如果当天的收盘价高于前一天,则每天标记为1,如果价格低于前一天,则标记为-1.
Momentum, in turn, is a classification: each day is labeled 1 if closing price that day is higher than the day before, and −1 if the price is lower than the day before.
我的库存变化百分比如下:
I have stock change percentages as follows:
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
Momentum
应该是:[1,1,1,-1,1,1]
.
因此,如果我找到过去 n = 3天的平均动量,我希望价格动量为:
So if I'm finding the average momentum for the last n = 3 days, I want my price momentum to be:
Price_momentum = [Nan, Nan, 1, 1/3, 1/3, 1/3]
我设法使用以下代码使其正常工作,但这非常慢(数据集有5000多个行,执行需要10分钟).
I managed to use the following code to get it working, but this is extremely slow (the dataset is 5000+ rows and it takes 10 min to execute).
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()
推荐答案
您可以创建 rolling
对象:
You can create a rolling
object:
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()
在这里,np.where
是apply()
的替代方法,它通常很慢,应该作为最后的手段.
Here, np.where
is an alternative to apply()
, which is generally slow and should be used as a last resort.
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
这篇关于在python中查找价格动能的有效方法:平均一列的最后n个条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!