我的一门课遇到了一些麻烦。这个特定的类应该计算给定列表(包含日期和价格)的移动平均线并且没有。天数(由用户输入)。这是我的代码:
class Moving_Average:
def calculation(self, alist:list,days:int):
m = days
prices = [float(i) for i in alist[1::2]]
average = [0]* len(prices)
signal = ['']* len(prices)
for m in range(0,len(prices)-days+1):
average[m+2] = sum(prices[m:m+days])/days
if prices[m+2] < average[m+2]:
signal[m+2]='SELL'
elif prices[m+2] > average[m+2] and prices[m+1] < average[m+1]:
signal[m+2]='BUY'
else:
signal[m+2] =''
average = [round(average[i],2) for i in range(0,len(average))]
return average,signal
当我想计算 3 天的平均值时,这很好用。但是当我尝试计算以 2 天为输入的平均值时,它给了我一个索引错误。当我尝试输入 4 作为天数时,结果如下:
[0, 0, 33.81, 33.74, 33.51, 33.31, 33.28, 33.49, 33.85, 34.21, 34.43, 34.62, 34.75,
34.88, 34.86, 34.57, 34.26, 34.45, 34.69, 35.13, 35.59, 35.51, 0], ['', '', '', '',
'SELL', 'SELL', 'SELL', 'BUY', '', '', '', '', '', '', '', '', 'SELL', 'SELL', 'BUY',
'', 'SELL', 'BUY', ''])
什么时候应该:
[0, 0, 0, 33.81, 33.74, 33.51, 33.31, 33.28, 33.49, 33.85, 34.21, 34.43, 34.62, 34.75,
34.88, 34.86, 34.57, 34.26, 34.45, 34.69, 35.13, 35.59, 35.51], ['', '', '', '',
'SELL', 'SELL', 'SELL', 'BUY', '', '', '', '', '', '', '', '', 'SELL', 'SELL', 'BUY',
'', 'SELL', 'BUY', ''])
即它在末尾添加一个 0 而不是开头。