# Algorithmic Trading Strategy with Machine Learning and Python

## What is Algorithmic Trading Strategy ?

Developing an Algorithmic trading strategy with Python is something that goes through a couple of phases, just like when you build machine learning models: you formulate a strategy and specify it in a form that you can test on your computer, you do some preliminary testing or back testing, you optimize your strategy and lastly, you evaluate the performance and robustness of your strategy.

Trading strategies are usually verified by back testing: you reconstruct, with historical data, trades that would have occurred in the past using the rules that are defined with the strategy that you have developed.

This way, you can get an idea of the effectiveness of your strategy, and you can use it as a starting point to optimize and improve your strategy before applying it to real markets.

This relies heavily on the underlying theory or belief that any strategy that has worked out well in the past will likely also work out well in the future.

And any strategy that has performed poorly in the past will probably also do badly in the future.

### Let’s Build an Algorithmic Trading Strategy with Python and Machine Learning

This program uses the dual moving average crossover to determine when to buy and sell stocks.

```import pandas as pd
import numpy as np
from datetime import datetime
import matplotlib.pyplot as plt
plt.style.use("dark_background")```

You can download the data set we need for this purpose from here:

To store the data

```apple = pd.read_csv("AAPL.csv")
apple```

Let’s Visualize the data

```plt.figure(figsize=(12, 5))
plt.xlabel("May 27,2014 - May 25,2020 ")
plt.legend(loc="upper left")
plt.show()```

Create a Simple moving average with a 30 day window

```sma30 = pd.DataFrame()
sma30```

To create a Simple moving average 100 day window

```sma100 = pd.DataFrame()
sma100```

### Now let’s Visualize the new data

```plt.figure(figsize=(12,5))
plt.xlabel('May 27,2014 - May 25,2020')
plt.legend(loc='upper left')
plt.show()```

Now create a new Data Frame to store all the data

```data = pd.DataFrame()
data```

### Create a function to signal when to buy or sell stock

```def buySell(data):
sigPriceSell = []
flag = -1
for i in range(len(data)):
if data ['SMA30'][i] > data['SMA100'][i]:
if flag != 1:
sigPriceSell.append(np.nan)
flag = 1
else:
sigPriceSell.append(np.nan)
elif data['SMA30'][i] < data['SMA100'][i]:
if flag != 0:
sigPriceSell.append(data['apple'][i])
flag = 0
else:
sigPriceSell.append(np.nan)
else:
sigPriceSell.append(np.nan)

To store the buy and sell  data into a variable

```buySell = buySell(data)
# To show the data
data```

### Now let’s Visualize the data and strategy to buy and sell stock

```plt.style.use('classic')
plt.figure(figsize=(12,5))
plt.plot(data['apple'], label='Apple', alpha=0.35)
plt.plot(data['SMA30'], label='SMA30', alpha=0.35)
plt.plot(data['SMA100'],label='SMA100', alpha=0.35)
plt.scatter(data.index, data['Sell Signal Price'],label='Sell', marker='v', color='red')
plt.xlabel("May 27,2014 - May 25,2020")