I have a function that calculates moving average. But its giving me a wrong output for the "Buy" signal. here is my code:
def calculate(self, alist, days=2):
averages = []
signals = []
prices = [float(n) for n in alist[1::2]]
window = collections.deque(maxlen=days)
for price in prices:
window.append(price)
averages.append(0)
signals.append("")
if len(window) == days:
mavg = sum(window) / days
averages[-1] = mavg
if price < mavg:
signals[-1] = "SELL"
elif price > mavg:
signals[-1] = "BUY"
tol=0.01
averages[:] = ("%.2f" % avg if abs(avg)>=tol else ' ' for avg in averages)
return averages, signals
The function checks if the current day closing price was higher than the current day moving average. However, the buy condition is that the current day closing price should be higher than current day moving average and the previous day closing price should be lower than previous days moving average. How can make the changes to this?