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

时间:2016-04-29 07:20:37

标签: python excel pandas moving-average

指数移动平均线在此链接中说明: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也是如此(除非我设置选项min_periods = 20来计算aapl_df)。我们不需要计算EMA20的前19个值吗?我怀疑,在我使用的另一个软件中,为了计算EMA20,前19天EMA20的价值显示为空白。

2)使用ewm方法在大熊猫中进行EMA计算也是在滚动的基础上进行的。这意味着,2016-03-31的EMA20仅基于最后20个值(2016-03-03至2016-03-31,即aapl_df中的索引41-60)。同样,2016-03-30的EMA20仅基于最后20个值(2016-03-02至2016-03-30即aapl_df中的指数40-59)?这种怀疑已经出现,因为这种方法是“滚动”#34;在使用窗口选项计算SMA时明确提到,但对于EMA的计算则不然。

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

4)我目前正在使用上面提到的逻辑来计算EMA交叉,是否有使用熊猫的替代方法?

谢谢。

0 个答案:

没有答案