Python 错误 - 在 Numpy 数组上计算移动平均

1 投票
2 回答
842 浏览
提问于 2025-04-18 01:30

我对此感到很困惑,真的是挠头。
我正在尝试对一个从文本文件加载的numpy数组计算移动平均值。

我还想打印我的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()

相关问题:

2 个回答

1

closep > smas 改成 closep[-1] > smas[-1] 或者 closep[0] > smas[0],应该能解决你想要的效果。

选择 closep[-1] > smas[-1] 还是 closep[0] > smas[0],要看你的数据:最新的价格是 txt 文件的最后一行,还是第一行?再确认一下。

如果你想获取所有可能的“买入信号”和它们的收盘价,而不使用循环,可以这样做:

if stance == 'none':
    buyPrice_list=closep[19:][closep[19:] > smas] #change it to [:-19] if the current price is the first row.

这样 buyPrice_list 就会存储所有买入信号时的收盘价。可以看看布尔索引的相关内容,了解更多信息,参考这个链接:http://wiki.scipy.org/Cookbook/Indexing

1

如果你有一个一维的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

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

撰写回答