MA和MACD的Python函数有“ValueError:不允许负尺寸”

时间:2016-01-19 14:49:42

标签: python pandas finance technical-indicator

我正在尝试使用pandas分析csv中的历史数据。我从Quantopian发现没有talib(无法安装),我们可以使用函数代码进行分析。但是,当我使用MA和MACD函数进行anlayze时,我遇到了 MA没有正确计算 2. MACD部分有“ValueError:不允许负尺寸” 我应该纠正哪一部分?

我的代码如下:

import numpy  
import pandas as pd

#Moving Average  
def MA(df, n):  
    MA = pd.Series(pd.rolling_mean(df['Close'], n), name = 'MA_' + str(n))  
    df = df.join(MA)  
    return df

#MACD, MACD Signal and MACD difference  
def MACD(df, n_fast, n_slow):  
    EMAfast = pd.Series(pd.ewma(df['Close'], span = n_fast, min_periods = n_slow - 1))  
    EMAslow = pd.Series(pd.ewma(df['Close'], span = n_slow, min_periods = n_slow - 1))  
    MACD = pd.Series(EMAfast - EMAslow, name = 'MACD_' + str(n_fast) + '_' + str(n_slow))  
    MACDsign = pd.Series(pd.ewma(MACD, span = 9, min_periods = 8), name = 'MACDsign_' + str(n_fast) + '_' + str(n_slow))  
    MACDdiff = pd.Series(MACD - MACDsign, name = 'MACDdiff_' + str(n_fast) + '_' + str(n_slow))  
    df = df.join(MACD)  
    df = df.join(MACDsign)  
    df = df.join(MACDdiff)  
    return df


data = pd.read_csv("NAIM.csv", index_col='Stock', usecols =[0,6])

print data.head(3)
vol = data['Close']
print vol
print MA(data,5)
print MACD(data,12,26)

csv文件如下:

Stock,Date,Time,Open,High,Low,Close,Volume
NAIM,2015-01-02,00:00:00,2.9,3.0,2.9,3.0,46900
NAIM,2015-01-05,00:00:00,2.95,3.05,2.92,3.05,225900
NAIM,2015-01-06,00:00:00,2.95,2.96,2.9,2.9,682000
NAIM,2015-01-07,00:00:00,2.88,2.95,2.88,2.9,160900
          .
          .
          .
NAIM,2016-01-06,00:00:00,2.48,2.61,2.47,2.6,3260900
NAIM,2016-01-07,00:00:00,2.64,2.74,2.6,2.65,3906100
NAIM,2016-01-08,00:00:00,2.65,2.71,2.62,2.64,1875000
NAIM,2016-01-11,00:00:00,2.65,2.7,2.65,2.68,1089400
NAIM,2016-01-12,00:00:00,2.68,2.71,2.65,2.69,965200
NAIM,2016-01-13,00:00:00,2.69,2.74,2.69,2.73,2091500
NAIM,2016-01-14,00:00:00,2.71,2.71,2.66,2.66,1206000
NAIM,2016-01-15,00:00:00,2.66,2.67,2.62,2.62,738600

我的python shell显示了输出:

Output from Python Shell after run the script

1 个答案:

答案 0 :(得分:1)

EMAslow = pd.Series(pd.ewma(df['Close'], span = n_slow, min_periods = n_slow - 1))  

EMAfast = pd.Series(pd.ewma(df['Close'], span = n_fast, min_periods = n_slow - 1))

我认为您需要更改EMAfast才能使用:  min_periods = n_fast - 1

我认为您的快速EMA缺少完整时段会导致收敛值为负,并导致您的错误。