antonio_zeus
antonio_zeus

Reputation: 497

unable to loop through numpy arrays

I am really confused and can't seem to find an answer for my code below. I keep getting the following error:

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()

Now, as you will see my code below, I am trying to compare two numpy arrays, step by step, to try and generate a signal once my condition is met. This is based on stock Apple data.

Going from one point at a time so starting at index[0] then [1], if my prices is greater than or equal to smas (moving average), then a signal is produced. Here is the code:

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    

Upvotes: 0

Views: 274

Answers (2)

mgilson
mgilson

Reputation: 309841

You have numpy arrays -- smas is the output of np.convolve which is an array, and I believe that prices is also an array. with numpy,arr > other_arrwill return anndarray` which doesn't have a well defined truth value (hence the error).

You probably want to compare price with a single element from smas although I'm not sure which (or what np.convolve is going to return here -- It may only have a single element)...

Upvotes: 1

Two-Bit Alchemist
Two-Bit Alchemist

Reputation: 18457

I think you mean

if price >= smas

You have

if prices >= smas

which compares the whole list at once.

Upvotes: 0

Related Questions