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

时间:2014-04-05 19:44:35

标签: 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()

2 个答案:

答案 0 :(得分: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

您的代码段中包含许多与手头问题无关的代码。

答案 1 :(得分:1)

根据您的预期行为,将closep > smas更改为closep[-1] > smas[-1]closep[0] > smas[0]应该是解决方案。

closep[-1] > smas[-1]还是closep[0] > smas[0]取决于您的数据:最新价格,是txt文件的最后一行,还是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