Momentum Trading with Python



Introduction

Momentum trading is a technique where traders buy and sell financial assets after being influenced by recent price trends. They look to take advantage of upward or downward trends within the financial markets until the trend starts to fade.

Momentum trading strategies focus on price action and price movements rather than fundamental factors, such as company growth or economics. This is a form of technical analysis​ that is very popular with short-term traders. However, traders calculate momentum price projections based on historical price trends and data, and given the volatility of financial markets, prices can change and the market can move in an unforeseen direction at any time. The markets are also affected by news releases and other macroeconomic events​, which need to be taken into account when building a momentum trading strategy and risk management​ plan.

Momentum refers to the speed of price changes within a financial security. It is determined by many factors, the most significant being asset volume and volatility of the market. Momentum traders look to enter and exit positions quickly, therefore they often prefer markets with high liquidity, such as the https://www.cmcmarkets.com/en-gb/forex-trading forex market or https://www.cmcmarkets.com/en-gb/markets-shares share market. Liquid markets are also particularly volatile and this means that momentum traders can take advantage of short trades through price swings, which is similar to other short-term trading strategies, such as day trading.

Trend following is another trading strategy that is used to identify https://www.cmcmarkets.com/en-gb/trading-guides/forex-trend trendlines ​within price charts when trading assets. Trend following and momentum strategies share similarities in that they both focus on price action, buy high on uptrends and sell low on downtrends. However, whereas momentum based trading relies on aspects of fundamental analysis to make predictions, trend followers tend to focus solely on price and the size of their trades. This is partially to reduce time and make quicker trades, but also to help reduce losses. Trend followers measure their position size with the trend rather than placing a large amount of capital in one position.

Whereas momentum strategies focus on following the current trends of an asset, https://www.cmcmarkets.com/en-gb/trading-guides/swing-trading swing trading​ takes a different approach to this. Instead, swing traders trade within ranges and tend to focus on buying and selling at support and resistance levels. As they trade on short-term price changes, most swing trades usually only last for a short duration, while momentum trades can last either in the short-term or long term, depending on the strength of a trend. Swing traders also do not take into account fundamental and economic factors that may have an effect on price trends.

Momentum in trading is often influenced by timeframe. Although some momentum traders prefer to take positions in the long-term, one of the most appropriate strategies for trading on momentum is the short-term approach of day trading. The aim of https://www.cmcmarkets.com/en-gb/trading-guides/day-trading day trading​ is to enter and exit multiple positions as quickly as possible throughout the day, with the aim of making a profit from small price movements. Therefore, momentum traders look for markets and securities with a high volume, so that they can buy and sell stocks quickly without interruption.

If each security has a range of at least $5, this is considered profitable enough for momentum intraday trading. Smaller price movements are more suited to scalping strategies, which are very common within the forex market, where currencies fluctuate by a number of ‘pips’.

As we have already discussed, momentum strategies are arguably the most useful for volatile markets, where there is a constant stream of traders. With this in mind, momentum in share trading is one of the most monitored markets. Share trading is a financial market where stocks are constantly changing in price, due to external factors. These include aspects of fundamental analysis, such as company earnings reports, updated P/E ratios and takeover bids. https://www.cmcmarkets.com/en-gb/trading-guides/company-fundamentals Company analysis​ is an important process of stock screening when a trader is interested in momentum in share trading.

The share market also applies to https://www.cmcmarkets.com/en-gb/trading-guides/what-is-an-exchange-traded-fund exchange-traded funds​ (ETFs), which are investment funds that grant a trader access to a collection of underlying assets. Various ETFs seek to track the performance of momentum-based indices within the stock market, most often large cap or blue-chip stocks, where is a constant stream of price action. Developing an ETF momentum trading strategy follows the same protocol as the share market, although you will be trading on multiple securities at once, rather than a single share.

Below are some of the most popular and efficient technical indicators for a momentum trader to succeed in their strategy. The best momentum indicators tend to focus on price action rather than a stock’s long-term economic situation. (See Articles Indicator Techniques where we to explain your uses with python RSI, Moving Average, Average directional index and Moving average convergence divergence (MACD).

Momentum Trading

Momentum is a phase in which an asset appears to be moving based on past changes in prices rather than due to any stock specific fundamental or news. When prices move higher in reaction to higher prices is known as a Bull phase, and when prices move lower just because they'd been going lower it's known as a Bear phase.

A momentum run is clearly seen with the candlestick charts where green represent up days and red represents down days. On the chart you can see that up appears to be in a bowl momentum phase for a few months in 2014 and is hugging what is known as a trend line.

A trend line is a straight line that connects two or more points which can be temporary highs or lows, since stock prices tend to be trendy. Trend lines that connect the highest or lows in a stock's price history, can help identify the current trend and predict what the stock price might do in the future. Volume (red box in the chart) is critical to confirming momentum trends. Technical analysts use trend lines above and below a series to identify potential buy or sell signals.

Figure 2: Momentum Trends

Quantitative traders need a measure that is more objective but still versatile. They use moving averages to clearly see stock price trends that may not be apparent in a forest of price bars. The slope of a moving average's line can show you whether a stock is an upward or downward trend and can be used to generate trading signals.

Momentum traders use moving or rolling averages to identify trends and specified trade entry and exit parameters. You saw earlier that a trend line is a good way to look at whether a stock is in a sustain momentum phase, either a Bull or Bear phase. The key word here is sustained(sostenido). Trends don't tell us whether the trend will continue or will break abruptly. This is where moving averages and crossovers come in.

Figure 3: Moving Averages Short and Long

Let's add some moving averages and look at the 2014-15 period when the stock was in a Bull momentum phase. We'll demonstrate this on the same chart you saw earlier, but with some added lines. The slope of the moving average line shows whether the stock is in an upward or downward trend. A simple moving average is just the average of the close price over a specified period. It is sometimes hard to spot a trend in a forest of price pars. The slope of rolling averages or moving averages can tell you whether a stock is in an uptrend or downtrend.

Figure 4: Moving Averages Short and Long

A 50-day simple moving average is the sum of all the closing prices in the 50-day period divided by 50. You can see this on the plot where the green line begins 50 days after the first price data point red and exponentially weighted moving average works the same as a simple moving average except the most recent prices are given more weight in the average than the older prices. Here you see the closing price plotted along with a 10-day and 50-day simple moving average. Each closing price in the window is equally weighted as opposed to an exponential average where more recent prices are given a heavier weight.

Figure 5: Simple Moving Averages 50 Day

This gives you an indicator that more closely reflects current market conditions while still including earlier data.

A very common way to obtain a buy or sell signal is to look for moving average crossovers in stock charts. This means computing two moving averages of different lengths and waiting for one to cross over the other. The direction of the cross will indicate the direction of the momentum. At least that's what technical traders believe. Volume is once again a critical component in determining whether the crossover is a real change in trend or temporary.

A Bear cross is when the shorter moving average moves below the longer moving average, and a Bull cross is when the shorter moving average moves above a longer moving average. Traders take a long position after a Bull cross and a short position in a stock after a Bear cross. They hold that position while the cross is in place. They switch positions when the bowl cross moves into a Bear cross or vice versa.

We can see here that there are four points where the averages cross each other. Assume you are currently long the stock, the first two crossings come close to each other and indicate a quick sell and then buy back phase, but the second two crossings predict a longer up face. This can be one way to make profits using moving average crossovers. However, since most traders are watching the same signals, there is no guarantee these will work in the real world. For that you will need to develop more complex trading strategies based on more unconventional trading signals.

Figure 6: Simple Moving Bear and Bell Cross

A very common way to obtain a momentum signal is to look for moving average crossovers. This mean computing two moving averages of different lengths, and waiting for one to cross the other. The direction of the cross will indicate the direction of the momentum.

Next let's look at how you choose the size of your moving average window or length. Choosing moving average length is very complicated. There are many choices of lengths such as 20, 30, 50, 65, 200 etcetera. In fact, any integer is a possible choice.

So the tendency is to look at the chart and find the two moving averages that seem to fit the given chart nicely, and then use that as a trading strategy for all stocks or even for the same stock in a future time period. This is known as over-fitting and you need to be aware of the danger of over-fitting. What works in one time period may not work in another time period, even for the same stock.

Choosing Moving Average Lengths is very complicated. There are many choices of lengths such as 20, 30, 50, 65, 200, etc. in fact any integer is a possible choice. So you need to be aware of the dangers of Overfitting.

The reason is the choice of lengths will strongly affect the signal you receive from your moving average crossover strategy. There may be better windows and you can attempt to find them with robust optimization techniques. However, it's incredibly easy to over-fit your moving window lengths. So, Dangers of overfitting the choice of lengths will strongly affect the signal that you receive from your moving average crossover strategy. There may be better windows and attempts to find them can be made with robust optimization techniques. Hovewer, it is incredibly easy overfit your moving window lengths.

Figure 7: Simple Moving Averages with Different Lengths

One approach is to use moving average crossover ribbons, draw many moving averages at a time, and attempt to extract statistics from the shape of the ribbon rather than any two moving averages. You can see how ribbons look here. You can combine quantitative measures of ribbon shape and so generate a trading signal.

Figure 8: Moving Average Crossover

Last we will look at two methods for evaluating or scoring the strength of a combination of moving average signals with different window lengths. The first is a distance metric and the second is correlation. One way of scoring is to use a distance metric. You can use a distance metric to see how far away from some given ranking our ribbon is. Here we combine ribbons to come up with a one to 10 ranking which we normalized to a score of zero to one. A perfectly increasing order of ribbons results in a score of zero. This can be a signal to buy or go long. A perfectly decreasing order of ribbons results in a score of one, this can be a signal to sell or go short.

Figure 9: Scoring Moving Averages Distance Metric

After ranking the rolling means and normalizing the scores, we plot them on the price chart. We see a number of strong cell signals followed by a weak buy signal another strong sell signal and then a weak buy signal. Scoring Moving Average Distance Metric. We see a number of strong sell signals and two buy signals towards the end of the data.

Next we will look at what happens after the final buy signal. When we look at what happens after the buy signal from the previous chart. We see that the stock price rises for bit and then drops by about 20-30 percent over the next few months, not good. So you have to constantly be on the lookout for better signals.

Another slightly better way maybe to use correlation to rank ribbons. You can use a correlation metric, a perfectly increasing order of ribbons results in a score of one, this can be a signal to buy or go long. A perfectly decreasing order of ribbons results in a score of negative one, this can be a signal to sell or go short. First, we rank the ribbons using a Spearman's correlation and normalize the score once again. A score close to one means a buy signal and a score close to negative one is a sell signal. This is somewhat better since it triggered three sell signals pretty close to the short-term top of the stock. This may be worth exploring some more.

A Score close to 1 means a buy signal and a score close to -1 is a sell signal. This is somewhat better since it triggered 3 sell signal pretty close to the short term top of the stock. This may be worth exploring some more.

Figure 10: Correlation to Rank Ribbons

Momentum Trading with Python

Moving Average Crossover

A very common way to obtain a momentum signal is to look for moving average crossovers. This means computing two moving averages of different lengths, and waiting for one to cross the other. The direction of the cross will indicate the direction of the momentum.

We'll demonstrate this on some real asset data.

#importing variables

import pandas as pd

import numpy as np

import datetime as dt

import pandas_datareader as pdr

import seaborn as sns

import matplotlib.pyplot as plt

data = "dow_jones.csv"

df = pd.read_csv(data)

all_data = pd.DataFrame()

all_data =df

\# create 20 days simple moving average column

all_data['30_SMA'] = all_data['Close'].rolling(window = 30, min_periods = 1).mean()

\# create 50 days simple moving average column

all_data['200_SMA'] = all_data['Close'].rolling(window = 200, min_periods = 1).mean()

\# display first few rows

print(all_data.head())

all_data['Signal'] = 0.0

all_data['Signal'] = np.where(all_data['30_SMA'] > all_data['200_SMA'], 1.0, 0.0)

all_data['Position'] = all_data['Signal'].diff() #diff() out[i]=a[i+1]-a[i]

\# display first few rows

print(all_data.head())

fig = plt.figure(facecolor = 'white', figsize = (20,10))

ax0 = plt.subplot2grid((6,4), (1,0), rowspan=4, colspan=8)

ax0.plot(all_data['Close'],color = 'r',label = 'Close')

#all_data['CloseBar']=all_data['12Ewm']

#all_data['CloseBar'].plot.bar(label='e', width=0.8)

ax0.plot(all_data['30_SMA'], color = 'b',label = '30-day SMA')

ax0.plot(all_data['200_SMA'], color = 'g', label = '200-day SMA')

ax0.set_facecolor('ghostwhite')

plt.plot(all_data[all_data['Position'] == 1].index, all_data['30_SMA'][all_data['Position'] == 1], #index() method only returns the first occurrence of the value.

 '^', markersize = 15, color = 'g', label = 'buy')

\# plot ‘sell’ signals

plt.plot(all_data[all_data['Position'] == -1].index, 

 all_data['30_SMA'][all_data['Position'] == -1], 

 'v', markersize = 15, color = 'r', label = 'sell')

plt.legend()

#ax0.legend(['Close','20_SMA','50_SMA','Position'],ncol=5, loc = 'upper left', fontsize = 15)

plt.title("Moving Average Crossover", fontsize = 20)

We can see here that there are five crossing points once both averages are fully populated. The first seems to be indicative of a following upturn, second of a downturn and so on.

Choosing Moving Average Lengths

WARNING: Overfitting

The choice of lengths will strongly affect the signal that you receive from your moving average crossover strategy. There may be better windows, and attempts to find them can be made with robust optimization techniques. However, it is incredibly easy to overfit your moving window lengths. For an exmaple of this see the Dangers of Overfitting.

An extended version of the moving average crossover system is the Moving Average Ribbon. This moving average strategy is created by placing a large number of moving averages onto the same chart (the chart shown below uses 8 simple moving averages). One must factor the time horizons and investment objectives while selecting the lengths and type of moving averages. When all the moving averages are moving in the same direction, the trend is said to be strong. Trading signals are generated in a similar manner to the triple moving average crossover system, the trader must decide the number of crossovers to trigger a buy or sell signal. Traders look to buy when the faster moving averages cross above the slower moving averages and look to sell when the faster moving averages cross below the slower moving averages.

References