I am scratching my head on this, as I am really confused. I am trying to compute a moving average on a numpy array. The numpy array is loaded from a txt file.
I also try to print my smas function (the moving average that I am computing on the loaded data) and fail to do so!
here is the code.
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
here is the error:
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()