# Stock Trading Strategy Using DEMA & Python

Algorithmic Trading Using the DEMA indicator

*Disclaimer: **The material in this article is purely educational and should not be taken as professional investment advice. Invest at your own discretion.*

The **Double Exponential Moving Average** or **DEMA** for short is a technical indicator that uses two exponential moving averages (EMA) to get rid of lag. It was brought to light in an article by Patrick Mulloy called “Smoothing Data With Faster Moving Averages”.

# How To Calculate DEMA ?

To Calculate DEMA, you can use a simple formula. The formula Gets the Exponential Moving Average for N-look back periods, let’s call this EMA1.

The formula then takes EMA1 multiplies it by 2 and subtracts that value with the EMA of EMA1 for the same N-look back periods.

That sounds complicated but it is quite simple, let’s take a look at the equation below:

DEMA = 2 * EMA_N — EMA of EMA_N

Where:

EMA_N = The EMA for N look back periods

ENA of EMA_N = The Exponential Moving Average for N look back periods of the EMA for N look back periods (EMA_N)

# What’s The Trading Strategy ?

When the short Term DEMA (20 days) crosses above the long term DEMA (50 days) that would be a bullish signal and so you would buy the stock and when the short term DEMA (20 days) crosses below the long term DEMA (50 days) that would be a bearish signal and so you would sell the stock.

When the short Term DEMA (20 days) crosses above the long term DEMA (50 days) buy

When the short term DEMA (20 days) crosses below the long term DEMA (50 days) sell

If you prefer not to read this article and would like a video representation of it, you can check out the **YouTube Video** below. It goes through everything in this article with a little more detail, and will help make it easy for you to start programming . Or you can use both as supplementary materials for learning !

If you are interested in reading more on algorithmic trading then you might want to read Hands-On Machine Learning for Algorithmic Trading: Design and implement investment strategies based on smart algorithms that learn from data using Python. The book will show you how to implement machine learning algorithms to build, train, and validate algorithmic models. It will also show you how to create your own algorithmic design process to apply probabilistic machine learning approaches to trading decisions, and the book will show you how to develop neural networks for algorithmic trading to perform time series forecasting and smart analytics.

# Programming

First, I will put a description about the program in comments, this way when I look back at the program I can read the description and know what the program is suppose to do.

`#Description: This program uses the Double Exponential Moving Average (DEMA) to determine when to buy and sell stock`

Next, I will import the libraries that I plan on using throughout the program and give the plot a style.

`#Import the libraries`

import pandas as pd

import numpy as np

import matplotlib.pyplot as plt

plt.style.use('fivethirtyeight')

Now, I want to upload the stock data. The stock data set contains information on Amazon (AMZN) stock from March 04, 2019 to August 14, 2020. Since I am using Google Collab website to write this program, I need to use their library to upload the data.

`#Load the data`

from google.colab import files # Use to load data on Google Colab

files.upload() # Use to load data on Google Colab

The data has been uploaded, now I want to store the data into a data frame, have the index set to be the date instead of integer values and show the data.

`#Store the data (The data is from 2019-Mar-04 to 2020-Aug-14)`

df = pd.read_csv('AMZN_Stock_Data.csv')

#Set the date as the index

df = df.set_index(pd.DatetimeIndex(df['Date'].values))

#Show the data

df

Visually show the close price to see the direction of the stock close price.

`#Visually show the close price`

df['Close'].plot(figsize=(12.2,6.4)) #Plot the data

plt.title('Close Price for AMZN ')

plt.ylabel('USD Price ($)')

plt.xlabel('Date')

plt.show();

It’s time to create a function to calculate the Double Exponential Moving Average (DEMA).

DEMA = 2 * EMA_N — EMA of EMA_N

#Create a function to calculate the Double Exponential Moving Average (DEMA)

def DEMA(data, time_period, column):

#Calculate the Exponential Moving Average for some time_period (in days)

EMA = data[column].ewm(span=time_period, adjust=False).mean()

#Calculate the DEMA

DEMA = 2*EMA - EMA.ewm(span=time_period, adjust=False).mean()return DEMA

Now that the calculation for DEMA is done, I want to create two new columns and store the Short Term DEMA (a DEMA with a 20 day look back time period) and the Long Term DEMA (a DEMA with a 50 day look back time period) in them.

`df['DEMA_short'] = DEMA(df, 20, 'Close') #Store the short term DEMA`

df['DEMA_long'] = DEMA(df, 50, 'Close') #Store the long term DEMA

Let’s plot the data.

`#Plot the chart`

#Create a list of columns to keep

column_list = ['DEMA_short', 'DEMA_long', 'Close']

df[column_list].plot(figsize=(12.2,6.4)) #Plot the data

plt.title('DEMA for AMZN')

plt.ylabel('USD Price ($)')

plt.xlabel('Date')

plt.show();

It’s time to create the strategy. The strategy will give us the buy and sell signals so that we know at which and price and when to buy & sell the stock. The strategy tells us to buy when the Short Term DEMA crosses above the Long Term DEMA and to sell when the Short Term DEMA crosses below the Long Term DEMA.

So, to do this I will create a function to store the signals into the data frame.

`def DEMA_Strategy(data):`

buy_list = [] #Create a list to store the price at which to buy

sell_list = [] #Create a list to store the price at which to sell

flag = False #Create a flag to determine when the indicators cross

#Loop through the data

for i in range(0,len(data)):

#Check if the Short Term DEMA crosses above the Long Term DEMA

if data['DEMA_short'][i] > data['DEMA_long'][i] and flag == False:

buy_list.append(data['Close'][i])

sell_list.append(np.nan)

flag = True

#Check if the Short Term DEMA crosses below the Long Term DEMA

elif data['DEMA_short'][i] < data['DEMA_long'][i] and flag == True:

buy_list.append(np.nan)

sell_list.append(data['Close'][i])

flag = False

else:#Else they didn't cross

buy_list.append(np.nan)

sell_list.append(np.nan)

#Store the Buy and Sell signals in the data set

data['Buy'] = buy_list

data['Sell'] = sell_list

Let’s run the strategy to get the buy and sell signals.

`#Run the Strategy to get the buy and sell signals`

DEMA_Strategy(df)

Plot the buy and sell signals to visually show when to buy and sell the stock.

`# Visually Show The Stock Buy and Sell Signals`

#Create and plot the graph

plt.figure(figsize=(12.2,4.5)) #width = 12.2in, height = 4.5

plt.scatter(df.index, df['Buy'], color = 'green', label='Buy Signal', marker = '^', alpha = 1) #Plot the buy signal

plt.scatter(df.index, df['Sell'], color = 'red', label='Sell Signal', marker = 'v', alpha = 1) #Plot the sell signal

plt.plot( df['Close'], label='Close Price', alpha = 0.35)#plt.plot( X-Axis , Y-Axis, line_width, alpha_for_blending, label)

plt.plot( df['DEMA_short'], label='DEMA_short', alpha = 0.35) #plot the Short Term DEMA

plt.plot( df['DEMA_long'], label='DEMA_long', alpha = 0.35) #plot the Long Term DEMA

plt.xticks(rotation=45)#Rotate the dates 45 degrees

plt.title('Close Price History Buy / Sell Signals')

plt.xlabel('Date',fontsize=18)

plt.ylabel('Close Price USD ($)',fontsize=18)

plt.legend( loc='upper left')

plt.show()

So, it looks like the strategy does well for this data set,

but remember that this indicator is not perfect and the strategy doesn’t guarantee success.

A lot more testing is needed to be done before using this strategy and you may want to use other indicators with this strategy for more information on when to buy and sell.

That’s it, we are done creating this program ! If you want to start an investment portfolio, then sign up with WeBull using this link and get **4 FREE stocks**** **(2 stocks just for signing up and 2 stocks for depositing $100 or more for new users). It’s 4 free stocks that you can either sell, play with or create your own trading strategy with. You can just sign up and not deposit $100, but the deal will expire and you won’t be able to get the extra 2 free stocks later (24 hours after signing up) if you decide to just sign up, so why not get the extra 2 stocks by depositing $100? I think it’s a great deal for a limited time and FREE money!

Thanks for reading this article I hope it’s helpful to you all! If you enjoyed this article and found it helpful please leave some claps to show your appreciation. Keep up the learning, and if you like machine learning, mathematics, computer science, programming or algorithm analysis, please visit and subscribe to my YouTube channels (randerson112358 & compsci112358 ).