[英]python error - moving average on numpy array
I am scratching my head on this, as I am really confused. 我对此感到挠头,因为我真的很困惑。 I am trying to compute a moving average on a numpy array.
我正在尝试计算一个numpy数组的移动平均值。 The numpy array is loaded from a txt file.
numpy数组是从txt文件加载的。
I also try to print my smas function (the moving average that I am computing on the loaded data) and fail to do so! 我也尝试打印我的smas函数(我正在加载的数据上计算的移动平均值),但没有这样做!
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()
If you have a 1-D numpy array, there's a really slick way of doing moving averages using cumsum (via https://stackoverflow.com/a/14314054/1345536 ): 如果您有一维一维的numpy数组,则有一种非常巧妙的方式来使用cumsum(通过https://stackoverflow.com/a/14314054/1345536 )进行移动平均:
def moving_average(a, n=3) :
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
Your code snippet has a lot of code that is extraneous to the problem at hand. 您的代码段中有很多与手头问题无关的代码。
Change closep > smas
to closep[-1] > smas[-1]
or closep[0] > smas[0]
should be the solution, according to your intended behavior. 根据您的预期行为,将
closep > smas
更改为closep[-1] > smas[-1]
或closep[0] > smas[0]
应该是解决方案。
Whether to closep[-1] > smas[-1]
or closep[0] > smas[0]
depends on your data: the most current price, is it the last row of the txt
file, or the first in the txt
file? 是否
closep[-1] > smas[-1]
或closep[0] > smas[0]
取决于数据:最新的价格,是它的最后一排txt
文件,或者在第一个txt
文件? Double check that. 仔细检查一下。
To get all the possible 'buy triggers' and their closing prices, without using a loop: 要获取所有可能的“购买触发器”及其收盘价,而无需使用循环:
if stance == 'none':
buyPrice_list=closep[19:][closep[19:] > smas] #change it to [:-19] if the current price is the first row.
Then buyPrice_list
stores all the closing prices at buy triggers. 然后,
buyPrice_list
将所有收盘价存储在购买触发器处。 See Boolean indexing, http://wiki.scipy.org/Cookbook/Indexing . 请参阅布尔索引, http://wiki.scipy.org/Cookbook/Indexing 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.