Photo by Ayadi Ghaith on Unsplash.com
A lot of trading strategies use moving average like SMA or EMA to identify trends. The strategy rules go something like “When the shorter period moving average crosses the longer period moving average, it is an upward trend” and vice versa.
This story is solely for general information purposes, and should not be relied upon for trading recommendations or financial advice. Source code and information is provided for educational purposes only, and should not be relied upon to make an investment decision. Please review my full cautionary guidance before continuing.
Unfortunately this over simplification has several issues:
First, we are reducing the trend to single point of information. In the process we are losing valuable information about the trend, e.g. length or strength.
Since moving averages are used, we now have to deal with lag due to the moving average window.
The moving average system is prone to false positives in case the lines cross multiple times. This is especially a problem when using moving averages with short windows as you can see from the chart below.
The Trendline System
One of the great things about automatic trading using a programming language is that you have a lot of flexibility and you are not bound to just using moving averages to determine trends.
So I came up with the following trend line system:
Convert the main price into a smoothed curve using Kernel regression to reduce the noise. This way we don’t have to deal with lag.
Create a main trend line for the smoothed price curve. This will give us an indication of the direction and strength of the price trend and allow us a draw a trend line.
Add two more trend lines that are calculated from the upper and lower pivot points. These lines will serve multiple purposes: Confirmation of the main price trend, support and resistance lines, determine breakouts, identify conversion and diversion.
Techniques Used
Here an overview of the techniques used in Python to create the trendline system. For details on how to calculate Pivot points on a smoothed curve, check out my post here.
Creating the smoothed curve using Kernel Regression
We will be using the statsmodel KernelReg function which uses the Nadaraya–Watson kernel regression.
Calculating the Pivot Points
To calculate the pivot points, we are going to use the argrelextrema() function of the scipy stats library.
Calculating the trends
For calculating the trends I used the numpy polyfit function using the least squared method.