如何在MS-Ex中测试从pandas-python获得的EMA交叉

2024-06-16 14:16:29 发布

您现在位置:Python中文网/ 问答频道 /正文

指数移动平均在这里解释如下:http://www.investopedia.com/terms/e/ema.asp

我使用了以下代码:

import pandas_datareader.data as web
from datetime import datetime
#
aapl_df = web.get_data_yahoo('AAPL', datetime(2016, 1, 1), datetime(2016, 03, 31))
aapl_df['SMA5'] = aapl_df['Adj Close'].rolling(window=5,center=False).mean()
aapl_df['SMA20'] = aapl_df['Adj Close'].rolling(window=20,center=False).mean()
aapl_df['EMA5'] = aapl_df['Adj Close'].ewm(span=5).mean()
aapl_df['EMA20'] = aapl_df['Adj Close'].ewm(span=20).mean()
#aapl_df['EMA20'] = aapl_df['Adj Close'].ewm(span=20,min_periods=20).mean() # commented to explain the min_periods
# Plot price vs various mean
aapl_df['2016'][['Adj Close', 'SMA20','EMA5', 'EMA20']].plot(figsize=(12,8));
# Reset the index
aapl_df = aapl_df.reset_index()
#Replace nan values with 0
aapl_df = aapl_df.fillna(0)
#
if aapl_df['Adj Close'].iloc[len(aapl_df)-1] > aapl_df['SMA20'].iloc[len(aapl_df)-1]:
    print  "20 day trendUP"
#==============================================================================
# Since the EMAs represent continuous functions, there is a crossing when,
# for a given row, (EMA_5 is less than EMA_20) and (the previous EMA_5 is
# greater than the previous EMA_20) -- or vice versa.
#==============================================================================
ema_previous5 = aapl_df['EMA5'].shift(1)
ema_previous20 = aapl_df['EMA20'].shift(1)
ema_crossing1 = (aapl_df['EMA5'] < aapl_df['EMA20']) & (ema_previous5 > ema_previous20)
ema_crossing2 = (aapl_df['EMA5'] > aapl_df['EMA20']) & (ema_previous5 < ema_previous20)
ema_crossing = ema_crossing1 | ema_crossing2
ema_crossing_dates = aapl_df.loc[ema_crossing, 'Date']
print ema_crossing_dates

一。 我的怀疑:

1)如果我查看aapl_df,SMA20列的前19个值为空。但EMA20的情况并非如此(除非我为计算aapl_df设置了min_periods=20选项)。我们不需要前19个值来计算EMA20吗?这个疑问的产生是因为,在我使用的另一个软件中,在计算EMA20时,前19天的EMA20值显示为空白。在

2)使用ewm法计算熊猫的EMA是否也在滚动基础上。也就是说,2016-03-31的EMA20仅基于最后20个值(对于2016-03-03至2016-03-31 ie;aapl_df中的索引41-60)。同样,2016-03-30的EMA20是否仅基于最后20个值(2016-03-02至2016-03-30 ie;aapl_df中的索引40-59)?这一疑问的产生是因为在窗口选项的SMA计算中明确提到了“滚动”方法,而对于EMA的计算则没有提及。在

3)我想对相同的数据在MS Excel中测试EMA20的正确性。我该怎么做?在

4)我目前正在使用上述逻辑来计算EMA交叉,是否有其他方法使用熊猫进行计算?在

谢谢。在


Tags: thedfclosedatetimemeanaaplemaadj