I'm trying to learn Backtesting 101. I found this example which is very simple but I do not quite understand some of the terms. I understand Moving Average algorithm which is to measure trends or to smooth the graph. But it the code, the author said # Take the difference of the signals in order to generate actual trading orders which I don't quiet understand what this means? Because from the code the signals is going to be between 0 and 1 why does it need o be diff again?

Here's the code in Python Pandas

def generate_signals(self):
  # Create DataFrame and initialise signal series to zero
  signals = pd.DataFrame(index=self.bars.index)
  signals['signal'] = 0

  # Create the short/long simple moving averages
  signals['short_mavg'] = pd.rolling_mean(bars['Adj Close'], self.short_window, min_periods=1)
  signals['long_mavg'] = pd.rolling_mean(bars['Adj Close'], self.long_window, min_periods=1)

  # When the short SMA exceeds the long SMA, set the ‘signals’ Series to 1 (else 0)
  signals['signal'][self.short_window:] = np.where(signals['short_mavg' [self.short_window:] > signals['long_mavg'][self.short_window:], 1, 0)

  # Take the difference of the signals in order to generate actual trading orders
  signals['positions'] = signals['signal'].diff()
  return signals

Becuase that positions is going to be used in the actual backtesting.


1 Answer 1


My understanding, in that context, is that signal indicates that you want to hold a share (signal is 1) or hold no shares (signal is zero). Therefore taking the diff will tell you if you want to buy (signal zero to 1, diff is 1), sell (signal 1 to zero, diff is -1) or do nothing (signal stays at zero or stays at 1, diff is zero).

  • 1
    $\begingroup$ Exactly. And the variable name 'positions' used here is unfortunate, would be better called 'trades' or 'position_change'. But the idea is exactly as Kiwiakos describes. (And to be honest my variable names are not always well chosen either...). $\endgroup$
    – nbbo2
    Jan 26, 2016 at 13:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.