无法循环numpy阵列
我真的很困惑,似乎无法找到我的代码下面的答案。我不断收到以下错误:无法循环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
我想你的意思
if price >= smas
你有
if prices >= smas
这整个名单一次比较。
好点!但问题是它仍然给我一个问题... –
你有numpy数组 - smas
是np.convolve
这是一个数组的输出,我相信prices
也是一个数组。与numpy,
arr> other_arr will return an
ndarray`没有明确定义的真值(因此错误)。
你可能想用一个单一的元素从smas
比较price
虽然我不知道哪个(或哪些np.convolve
会回到这里 - 这可能只有一个元素)...
我想这是一个很好的观点。现在价格和smas都有相同长度的元素。我的目标是逐字比较每个元素中的第一个元素,并继续前进,直到我的if语句变为真,然后继续前进,直到我的elif为真。 –
是否有可能将smas转换为numpy数组后不同的格式?我会遇到麻烦做一个列表与一个numpy数组相同的逻辑? –
@antonio_zeus - 列表比较“按字典顺序”。例如第一个元素进行比较,然后第二个,然后第三个,直到其中一个元素是不同的和排序是不同元素比较的结果... – mgilson
你似乎在代码中存在一个错误:在价格价格循环中,如果price> = smas',那么这是行不通的,因为'prices'是一个列表或一个数组,因此不能相比较。我想你的意思是在那里写'价格'。 – Zak