gpt4 book ai didi

MA 和 MACD 的 Python 函数有 "ValueError: negative dimensions are not allowed"

转载 作者:太空宇宙 更新时间:2023-11-04 05:38:22 25 4
gpt4 key购买 nike

我正在尝试使用 pandas 分析 csv 中的历史数据。我从 Quantopian 中找到如果没有talib(安装失败),我们可以使用函数代码来分析。但是,当我使用 MA 和 MACD 函数进行分析时,我遇到了1. MA计算不正确2. MACD部分出现“ValueError: negative dimensions are not allowed”我应该更正哪一部分?

我的代码如下:

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

最佳答案

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 上缺少完整周期会导致负收敛值并导致您的错误。

关于MA 和 MACD 的 Python 函数有 "ValueError: negative dimensions are not allowed",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34879817/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com