1

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?

  • Try to use `numpy` module, it's not only faster, more memory efficient but also supports vector operations, so makes your code simpler. Also look into `pandas` as suggested here: http://stackoverflow.com/questions/14313510/moving-average-function-on-numpy-scipy – Aleksander Lidtke Nov 09 '13 at 00:30
  • @AleksanderLidtke- Am not allowed to use numpy or pandas for this one. – captain morgan Nov 09 '13 at 00:35
  • add `days = float(days)` as the first line in the function definition? My guess is that the division by `days` is using integer division. Or you can add `from __future__ import division` at the top of your module. – Alok-- Nov 09 '13 at 00:53

0 Answers0