# Trading Strategy with Machine Learning

In this article I will take you through a Trading Strategy with Machine Learning, which can be used to determine when you should buy stocks and when you should sell. Generally it is not easy to predict stock market, but building a Trading Strategy using Machine Learning can make it easy.

## Trading Strategy with Machine Learning

The trading strategy I will use in this article is the Triple Moving Average System which is also known as Three Moving Average System. This strategy can be used to generate the signals conveying when to invest in the Stock market or when to sell. It uses the strategy of three moving averages – one fast/short, second middle/medium, one slow/long.

The strategy is based on to invest in the stock market when the fast/short moving average is higher than the middle moving average and the middle average is higher than the slow/long moving average otherwise vice versa.

Also Read: Types of Machine Learning Systems.

## Building a Trading Strategy with Machine Learning

I hope now you know how to determine when to buy and sell stocks with a training strategy. Now we will implement the theory of three moving averages using Machine Learning to predict when to buy and sell stocks. Let’s start by importing the basic libraries:

```.wp-block-code {
border: 0;
}

.wp-block-code > div {
overflow: auto;
}

.hljs {
box-sizing: border-box;
}

.hljs.shcb-code-table {
display: table;
width: 100%;
}

.hljs.shcb-code-table > .shcb-loc {
color: inherit;
display: table-row;
width: 100%;
}

.hljs.shcb-code-table .shcb-loc > span {
display: table-cell;
}

.wp-block-code code.hljs:not(.shcb-wrap-lines) {
white-space: pre;
}

.wp-block-code code.hljs.shcb-wrap-lines {
white-space: pre-wrap;
}

.hljs.shcb-line-numbers {
border-spacing: 0;
counter-reset: line;
}

.hljs.shcb-line-numbers > .shcb-loc {
counter-increment: line;
}

.hljs.shcb-line-numbers .shcb-loc > span {
}

.hljs.shcb-line-numbers .shcb-loc::before {
border-right: 1px solid #ddd;
content: counter(line);
display: table-cell;
text-align: right;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
white-space: nowrap;
width: 1%;
}
```import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')``````

Now let’s load the data. I will scrape the data from yahoo finance. Pandas Data Reader module will help in scraping the information about stock prices from yahoo finance. I will load the data and read the first 5 rows from the data.

``````df = web.DataReader('TSLA', data_source='yahoo', start='2017-11-17', end='2020-06-20')

Before moving forward let’s visualize this data, to see what we are working with:

``````plt.figure(figsize=(16,8))
plt.title('Close Price History')
plt.plot(df['Close'])
plt.xlabel('Date',fontsize=18)
plt.ylabel('Close Price USD (\$)',fontsize=18)
plt.show()``````

## Calculating Three Moving Averages

Now, I will calculate all the three moving averages to setup our trading strategy. The three moving averages include one fast/short, second middle/medium, one slow/long. Let’s calculate these:

``````#Calculate the Short/Fast Exponential Moving Average
ShortEMA = df.Close.ewm(span=5, adjust=False).mean() #AKA Fast moving average
#Calculate the Middle Exponential Moving Average
MiddleEMA = df.Close.ewm(span=21, adjust=False).mean() #AKA Slow moving average
#Calculate the Long/Slow Exponential Moving Average
LongEMA = df.Close.ewm(span=63, adjust=False).mean() #AKA Slow moving average``````

Now, we have created the trading strategy, now let’s visualize it:

``````#Visualize the closing price and the exponential moving averages
plt.figure(figsize=(16,8))
plt.title('Tesla')
plt.plot(df['Close'], label = 'Close Price')
plt.plot(ShortEMA, label='Short/Fast EMA', color = 'red')
plt.plot(MiddleEMA, label='Middle/Medium EMA', color = 'orange')
plt.plot(LongEMA, label='Long/Slow EMA', color = 'green')
plt.xlabel('Date',fontsize=18)
plt.ylabel('Close Price USD (\$)',fontsize=18)
plt.legend(loc='upper left')
plt.show()`````` 