如何在 pandas 中添加移动日均线条件?

How to add conditions with moving day averages in pandas?

家庭作业问题需要帮助解决: 策略:每当价格突破50日均线时买入,3个交易日后卖出。我们平均能赚多少利润(百分比)?在交易日 x,我们说价格 "goes above" 50 天移动平均线,如果 (1) 价格在交易日 x-1 低于移动平均线,并且 (2) 价格在第x个交易日

如何将条件 [1] 和 [2] 合并到我当前的 50 天移动平均线代码中:

rol=stock.rolling(50).mean()

profitMade=((stock.shift(-3)-stock)/stock)

stock>rol

profitMade[stock>rol].mean()

样本数据集:股票和相应的日期:

Date
2002-05-23      1.196429
2002-05-24      1.210000
2002-05-28      1.157143
2002-05-29      1.103571
2002-05-30      1.071429
2002-05-31      1.076429
2002-06-03      1.128571
2002-06-04      1.117857
2002-06-05      1.147143
2002-06-06      1.182143
2002-06-07      1.118571
2002-06-10      1.156429
2002-06-11      1.153571
2002-06-12      1.092857
2002-06-13      1.082857
2002-06-14      0.986429
2002-06-17      0.922143
2002-06-18      0.910714
2002-06-19      0.951429

好的,这就是我所拥有的。不优雅,但我认为它完成了工作。

import datetime
import pandas as pd
import random

# Sample dataset
df = pd.DataFrame({'Date':sorted([datetime.date.today() - datetime.timedelta(days=i) for i in range(80)]), 'Price':[i for i in range(80)]})
df['Price'] = df['Price'].apply(lambda x: random.uniform(80,100))

>>>df
          Date      Price
0   2018-11-11  83.894664
1   2018-11-12  86.472656
2   2018-11-13  92.566676
3   2018-11-14  94.145586
..         ...        ...
77  2019-01-27  86.338076
78  2019-01-28  95.374173
79  2019-01-29  98.829077

[80 rows x 2 columns]

# MA calculation - borrowing from @jezrael's solution at 
seq = df.set_index('Date')['Price'].rolling(50).mean().rename('MA')
df = df.join(seq, on='Date')

# Set buy signals if current price is higher than 50-day MA
df['Buy'] = df['Price'] - df['MA'] > 0
# Lookbehind check to see that it was below MA at T-1
df['BelowMA'] = df['Price'] - df['MA'] <= 0
# Profit calculations
df['Profit'] = (df['Price'] - df['Price'].shift(-3))/df['Price']

最后,满足给定约束的行

>>> df.loc[(df['BelowMA'].shift(1)==True) & (df['Buy'] == True)]
          Date      Price         MA   Buy    Profit  BelowMA
54  2019-01-04  91.356371  89.634529  True  0.000697    False
56  2019-01-06  94.116616  89.623909  True  0.114375    False
60  2019-01-10  89.383369  89.254519  True -0.082870    False
63  2019-01-13  96.790575  88.977660  True  0.029314    False
69  2019-01-19  92.193939  89.052057  True  0.071259    False
74  2019-01-24  91.392465  89.302293  True  0.020673    False
76  2019-01-26  95.369195  89.292715  True  0.158250    False