0

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    
1
  • You seem to have a bug in the code: Within the for price in prices loop, you have if prices >= smas -- this can't work since prices is a list or an array, thus can't be compared. I think you meant to write price there. Commented Nov 15, 2014 at 21:04

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

I guess that's a good point. Right now price and smas both have the same length of elements. My goal is to literally compare the first element in each, and keep going forward until my if statement becomes true, then continue moving forward until my elif is true....
Is it possible to convert smas after it becomes a numpy array to a different format? Will I run into trouble doing the same logic with a list vs. a numpy array?
@antonio_zeus -- lists compare "lexicographically". e.g. the first element is compared, then the second, then the third until one of the elements is different and the ordering is the result of the comparison of the different elements...
would you say that I should create a loop for smas, in the sense that we only compare xth element? if so, how would I do that? sorry for my confusion!!
0

I think you mean

if price >= smas

You have

if prices >= smas

which compares the whole list at once.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.