我真的很困惑,似乎无法在下面找到我的代码的答案。我一直收到以下错误:
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数组,以便在满足条件后尝试生成信号。这是基于库存Apple数据。
一次从一个点开始,从索引[0]开始,然后[1],如果我的价格大于或等于smas(移动平均线),则产生信号。这是代码:
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 :(得分:1)
你有numpy数组 - smas
是np.convolve
的输出,它是一个数组,我相信prices
也是一个数组。与numpy,
arr&gt; other_arr will return an
ndarray`没有明确定义的真值(因此错误)。
您可能希望将price
与smas
中的单个元素进行比较,但我不确定哪个(或np.convolve
将返回此处 - 它可能只有一个单个元素)...
答案 1 :(得分:0)
我认为你的意思是
if price >= smas
你有
if prices >= smas
一次比较整个清单。