2014-04-07 57 views
0

我真的很困惑,似乎無法找到我的代碼下面的答案。我不斷收到以下錯誤:無法循環numpy陣列

File "C:\Users\antoniozeus\Desktop\backtester2.py", line 117, 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的陣列,一步一步,去嘗試,一旦我的條件得到滿足產生的信號。這是基於蘋果股票數據。

從一個點在一個時間去在索引所以開始[0]然後[1],如果我的價格是大於或等於形狀記憶合金(移動平均),那麼產生信號。下面是代碼:

def backTest(): 

    #Trade Rules 
    #Buy when prices are greater than our moving average 
    #Sell when prices drop below or moving average 

    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')}) 

    ## FIRST SMA 
    window = 10 
    weights = np.repeat(1.0, window)/window 
    '''valid makes sure that we only calculate from valid data, no MA on points 0:21''' 
    smas = np.convolve(closep, weights, 'valid') 

    prices = closep[9:] 

    for price in prices: 
     if stance == 'none': 
      if prices >= smas: 
       print "buy triggered" 
       buyPrice = closep 
       print "bought stock for", buyPrice 
       stance = "holding" 
       startTime = date 
       print 'Enter Date:', startTime 

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


       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:', endTime 
       endTime = date 
       timeInvested = endTime - startTime 
       totalInvestedTime += timeInvested 

       overallEndTime = endTime 

       numberOfTrades += 1 

     #this is our reset 
     previousPrice = closep  
+0

你似乎在代碼中存在一個錯誤:在價格價格循環中,如果price> = smas',那麼這是行不通的,因爲'prices'是一個列表或一個數組,因此不能相比較。我想你的意思是在那裏寫'價格'。 – Zak

回答

0

我想你的意思

if price >= smas 

你有

if prices >= smas 

這整個名單一次比較。

+0

好點!但問題是它仍然給我一個問題... –

1

你有numpy數組 - smasnp.convolve這是一個數組的輸出,我相信prices也是一個數組。與numpy, arr> other_arr will return an ndarray`沒有明確定義的真值(因此錯誤)。

你可能想用一個單一的元素從smas比較price雖然我不知道哪個(或哪些np.convolve會回到這裏 - 這可能只有一個元素)...

+0

我想這是一個很好的觀點。現在價格和smas都有相同長度的元素。我的目標是逐字比較每個元素中的第一個元素,並繼續前進,直到我的if語句變爲真,然後繼續前進,直到我的elif爲真。 –

+0

是否有可能將smas轉換爲numpy數組後不同的格式?我會遇到麻煩做一個列表與一個numpy數組相同的邏輯? –

+0

@antonio_zeus - 列表比較「按字典順序」。例如第一個元素進行比較,然後第二個,然後第三個,直到其中一個元素是不同的和排序是不同元素比較的結果... – mgilson