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:

```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import pandas_datareader as web
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')
df.head()
```

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()
```

**Also Read: 10 Machine Learning Projects to Boost your Portfolio.**

It is showing a promising picture of the stock prices with the consideration of all three moving averages. You can use this strategy in investing in stocks, considering you apply and analyse it on several scenarios. I hope you liked this article, feel free to ask your valuable questions in the comments section below.