python 错误 - numpy 数组上的移动平均值

标签 python arrays numpy moving-average

我对此很困惑,因为我真的很困惑。 我正在尝试计算 numpy 数组上的移动平均值。 numpy 数组是从 txt 文件加载的。

我还尝试打印我的 smas 函数(我在加载的数据上计算的移动平均值),但失败了!

这是代码。

def backTest():
    portfolio = 50000
    tradeComm = 7.95

    stance = 'none'
    buyPrice = 0
    sellPrice = 0
    previousPrice = 0

    totalProfit = 0

    numberOfTrades = 0
    startPrice = 0


    startTime = 0
    endTime = 0
    totalInvestedTime = 0
    overallStartTime = 0
    overallEndTime = 0

    unixConvertToWeeks = 7*24*60*60
    unixConvertToDays = 24*60*60
    date, closep, highp, lowp, openp, volume = np.genfromtxt('AAPL2.txt', delimiter=',', unpack=True,
                                                          converters={ 0: mdates.strpdate2num('%Y%m%d')})


    window = 20
    weights = np.repeat(1.0, window)/window
    smas = np.convolve(closep, weights, 'valid')

    prices = closep[19:]

    for price in prices:
        if stance == 'none':
            if prices > smas:
                print "buy triggered"
                buyPrice = closep
                print "bought stock for", buyPrice
                stance = "holding"
                startTime = unixStamp
                print 'Enter Date:', time.strftime('%m/%d/%Y', time.localtime(startTime))

            if numberOfTrades == 0:
                startPrice = buyPrice
                overallStartTime = unixStamp

            numberOfTrades += 1


        elif stance == 'holding':
            if prices < smas:
                print 'sell triggered'
                sellPrice = closep
                print 'finished trade, sold for:',sellPrice
                stance = 'none'
                tradeProfit = sellPrice - buyPrice
                totalProfit += tradeProfit
                print totalProfit
                print 'Exit Date:', time.strftime('%m/%d/%Y', time.localtime(endTime))
                endTime = unixStamp
                timeInvested = endTime - startTime
                totalInvestedTime += timeInvested

                overallEndTime = endTime

                numberOfTrades += 1

        previousPrice = closep

这是错误:

 Traceback (most recent call last):
  File "C:\Users\antoniozeus\Desktop\backtester2.py", line 180, in <module>
backTest()
  File "C:\Users\antoniozeus\Desktop\backtester2.py", line 106, in backTest
if prices > smas:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

最佳答案

如果您有一个一维 numpy 数组,那么有一种非常巧妙的方法可以使用 cumsum 进行移动平均(通过 https://stackoverflow.com/a/14314054/1345536 ):

def moving_average(a, n=3) :
    ret = np.cumsum(a, dtype=float)
    ret[n:] = ret[n:] - ret[:-n]
    return ret[n - 1:] / n

您的代码片段中有很多与当前问题无关的代码。

关于python 错误 - numpy 数组上的移动平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22885899/

相关文章:

python - 请帮我将以下 lambda 翻译成人类语言

python - Django url 模式顺序和正则表达式

arrays - Xcode:如何将可变长度数组输出到输出窗口?

python - 如何修复 “ValueError: not enough values to unpack (expected 2, got 1)”

python - 计算两个不同长度的 2d numpy 数组之间每行的逐元素匹配数

python - 对地理数据框中的点进行重新采样,使它们保持等距但在区域内

python - 我与 Python 进行数值集成的错误在哪里?

arrays - 根据几个条件从数据数组返回值

javascript - react /JSX : Iterating through an object with key/value pairs

python - 数组相等但视觉上不一样