We collect cookies to improve your browsing experience. By using our site, you agree to ourPrivacy Policy andTerms of Service.

A Basic Moving Average Strategy
Bubble Analytics Research26-Apr-2026

A Basic Moving Average Strategy

Summary:

Ticker:QQQ
Timeframe:Daily
Backtest Window:10yrs
Time Invested:44.01%
# Trades:116
Win Rate:45.68%
Total Return:289.46%
Max Drawdown:-16.91%
Sharpe Ratio:1.14
Profit Factor:2.18

It wouldn’t be a trading blog without a moving average strategy, so this weeks effort is built using a fast 9-period exponential moving average (EMA9) and a slower 31-period exponential moving average (EMA31) only, and the aim is to use EMA31 for trend confirmation and EMA9 price cross conditions for entry and exit timing.

As usual, to get things going we have downloaded 10 years worth of free daily OHLC bars for the Nasdaq 100 index (QQQ) into a dataframe named df, and the backtest itself is run using the backtesting.py library. Via our video and this article we will show you how to calculate the moving averages, overlay them onto price, generate trading signals, then run a full backtest.

The completed codebook along with our backtesting template can be downloaded via our GitHub profile, but for more detailed coding instruction you can refer to the video on our YouTube channel which shows you how to construct it from start to finish. Please note that the article strategy is for infotainment purposes only and should not be construed as financial advice.

Creating Exponential Moving Averages

Exponential moving averages place greater weight on more recent prices, which allows them to respond to price change movement slightly faster than simple moving averages.

In this strategy we calculate two EMAs based on Close prices: EMA9 and EMA31. The fast EMA9 tracks short-term momentum, while EMA31 moves slower and will act as a reference point to assess the prevailing trend. When EMA9 is above EMA31 we consider the market to be favouring bullish outcomes; when EMA9 is below EMA31 we assume the market is bearish and look for downside set ups.

We create 2 new columns in our dataframe (df) for our 2 moving averages, code as follows:

df["EMA9"] = df.Close.ewm(span=9).mean()
df["EMA31"] = df.Close.ewm(span=31).mean()

The chart below shows you price with the exponential moving averages overlaid:

Section 12

Trade Signal Generation

For trade signals, .iloc indexing is used to compare the current bar with prior bars to confirm that specific conditions have just occurred. Here, .iloc[i] represents the bar that has just closed, while .iloc[i-1] represents the bar immediately before it. So for example with the line (data.Close.iloc[i-1] < data.EMA9.iloc[i-1]), we are checking to see if yesterday’s close was below yesterday’s fast moving average (EMA9).

A buy signal is generated when EMA9 is above EMA31 signifying bullish conditions, and yesterdays close was below EMA9 but today’s close is back above it. A sell signal (short entry) is generated when EMA9 is below EMA31, signifying bearish conditions, and yesterday’s close was above EMA9 but today’s close is below it.

If neither condition is met, the signal remains 0 and no action is taken.

The signal function loops through each row of the dataframe and assigns a value of 1 (buy), 2 (sell), or 0 (do nothing) into a ‘signal’ column.

Our signal code looks like this:

def signal(data):
signal = [0] * len(df)
for i in range(0, len(df)):
if (data.Close.iloc[i-1] < data.EMA9.iloc[i-1]) &\
(data.Close.iloc[i] > data.EMA9.iloc[i]) &\
(data.EMA9.iloc[i] > data.EMA31.iloc[i]):
signal[i] = 1
elif (data.Close.iloc[i-1] > data.EMA9.iloc[i-1]) &\
(data.Close.iloc[i] < data.EMA9.iloc[i]) &\
(data.EMA9.iloc[i] < data.EMA31.iloc[i]):
signal[i] = 2
else:
signal[i] = 0
df["signal"] = signal
signal(df)

Running the Backtest

Once our signal column values are populated, we can then run the backtest. We define a SIGNAL function to take in the values of our signal column, then create a strategy class called MyStrat. Within MyStrat we initialise the SIGNAL function, create a price reference point that we can key from to set stop losses and profit targets, and then use IF statements to tell the backtesting program what action to take when a buy or sell signal is found.

In this case, if signal equals 1 we close any open short position and buy with 99% of available capital (size=0.99), using a 3% stop loss and a 5% profit target. If signal equals 2 we close any open long position and flip short with the same position sizing, a 1% stop loss, and a 6.5% profit target.

When we come to run the backtest, we tell it where to find our signal column values (df), which strategy class we want to run (MyStrat), define the starting capital allocation (cash=100_000), set it to use no leverage (margin=1), set a rule whereby we can only have one open position at a time (exclusive_orders=True), and tell it to factor in a 0.05% commission fee on both entry and exit for a total fee per trade of 0.1%.

The code looks like this:

def SIGNAL():
return df.signal
class MyStrat(Strategy):
def init(self):
super().init()
self.signal = self.I(SIGNAL)
def next(self):
super().next()
price = self.data.Close[-1]
if self.signal == 1:
if self.position.is_short or not self.position:
self.position.close()
self.buy(size=0.99, sl=0.97*price, tp=1.05*price)
elif self.signal == 2:
if self.position.is_long or not self.position:
self.position.close()
self.sell(size=0.99, sl=1.01*price, tp=0.935*price)
bt = Backtest(df, MyStrat, cash=100_000, margin=1, exclusive_orders=True, commission=0.0005)
stats = bt.run()
stats

Strategy Results

The strategy exposure time of 44.01% reduces market participation versus buy-and-hold, and while absolute return is lower than passive exposure, it delivers controlled risk with a relatively strong risk-adjusted profile evidenced by the low drawdown metrics. Stats are as follows:

Stats 28

Despite a modest win rate of 45.68%, the strategy still produces a positive expectancy due to a favourable risk-to-reward structure, where average winners far outweigh average losers. In order to visualise the drawdown profile, a profit and loss graph is included below:

Section 30

With 116 trades, we have more than enough to model risk via a Montecarlo simulation, which is reasonably good looking and emphasises some validity in the strategy.

Section 32

Overall the strategy appears to be reasonably effective at capturing directional momentum by combining short-term price crossover signals with higher-level trend confirmation. However, like most moving average systems, it can struggle in choppy sideways markets where repeated crossover events increase whipsaw risk, and entries are naturally lagging because confirmation only occurs after the crossover has already happened.

As always, further parameter optimisation, regime filtering, or volatility targeting may improve performance. This article strategy is presented for educational purposes only and should not be considered financial advice. For a detailed run through of the codebook, please watch the video below.

Share this article:

Explore our services

Recent Articles

Browse all articles