How to Use Algorithmic Trading With Machine Learning in Python

Zadhid Powell 09 May, 2022 • 5 min read

This article was published as a part of the Data Science Blogathon.

Trading in the 21st century has evolved exponentially since its commencement. Although, a few decades ago, it was very disorganized and slow because of the analog functionality. Meanwhile, modern computing technology has developed faster, sustainable, stress-free automated trading systems by orienting machine learning and artificial intelligence.

Whenever we talk about machine learning and AI in trading, it isn’t easy to elaborate without including Python programming language. With machine learning in Python, algorithmic trading systems have initiated delivering faster, human-free algorithmic trading opportunities.

As a result, trading robots have become a standard modern-day trading tool. Hence, algorithmic trading is gaining popularity because of the faster and human error-free trading functionality.

This article will cover the approaches to start algorithmic trading approaches with machine learning in Python.

Why Use Machine Learning in Algorithmic Trading?

Machine learning facilitates traders more than traditional algorithmic trading. For example, machine learning algorithms can find patterns by evaluating large data volumes, although conventional methods can process fewer amounts. Similarly, traders detect trading tendencies using machine learning and make decisions by putting the algorithm through its paces on historical data.

Furthermore, the development of current cloud systems has paved the way for a new era in sophisticated computing. Similarly, anyone can use cutting-edge computing to test and operate their machine learning algorithms using distributed cloud systems like the MQL5 Cloud Network.

Hence, machine learning in Python became even more popular because of the availability of backtesting technologies. Notably, requiring less computing power is impacting faster Python evolution.

Why Python for Algorithmic Trading?

Python, C++, Java, C#, and R are the five most common programming languages available to prospective traders. But Python offers some excellent features that make it the first choice.

  1. Python code is easy to read and understand. Less coding compared to other languages because of comprehensive libraries. So, less coding, more trading.
  2. It’s an interpreted language that executes the code statements, constructing a comprehensive debugging. Besides, the single error execution speeds up the entire construction process.
  3. Python has incredible computing power to subsidize your portfolio and scalability. Asides, fixing a new module in Python and making it extensive is more straightforward than any other language.
  4. It has an extensive support library consisting of the most popular programming language tasks within them in a simplistic method.

How to Integrate Python with MetaTrader 5 Trading Module

MetaTrader 5 is a third-party trading platform that offers packages designed for suitable and fast data processing and communication directly from the MetaTrader 5 terminal. The data received can be further used for statistical calculations and machine learning. It also has an online community called MQL5 Community for traders and developers to communicate, and developers can sell different trading solutions and make a career.

Let’s see how to integrate Python and MetaTrader 5:

1. Download the latest version of the Python programming language. Also, check “Add Python 3.10.1 to PATH%” to run the Python scripts directly from the PC command line.

2. Run the command line and run a command to install MetaTrader 5 with Python.

pip install MetaTrader5

3. Install Python libraries

pip install matplotlib
pip install pandas

4. Launch this script code to test the integration.

from datetime import datetime
import matplotlib.pyplot as plt
import pandas as pd
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
import MetaTrader5 as mt5
# connect to MetaTrader 5
if not mt5.initialize():
    print("initialize() failed")
    mt5.shutdown()
# request connection status and parameters
print(mt5.terminal_info())
# get data on MetaTrader 5 version
print(mt5.version())
# request 1000 ticks from EURAUD
euraud_ticks = mt5.copy_ticks_from("EURAUD", datetime(2020,1,28,13), 1000, mt5.COPY_TICKS_ALL)
# request ticks from AUDUSD within 2019.04.01 13:00 - 2019.04.02 13:00
audusd_ticks = mt5.copy_ticks_range("AUDUSD", datetime(2020,1,27,13), datetime(2020,1,28,13), mt5.COPY_TICKS_ALL)
# get bars from different symbols in a number of ways
eurusd_rates = mt5.copy_rates_from("EURUSD", mt5.TIMEFRAME_M1, datetime(2020,1,28,13), 1000)
eurgbp_rates = mt5.copy_rates_from_pos("EURGBP", mt5.TIMEFRAME_M1, 0, 1000)
eurcad_rates = mt5.copy_rates_range("EURCAD", mt5.TIMEFRAME_M1, datetime(2020,1,27,13), datetime(2020,1,28,13))
# shut down connection to MetaTrader 5
mt5.shutdown()
#DATA
print('euraud_ticks(', len(euraud_ticks), ')')
for val in euraud_ticks[:10]: print(val)
print('audusd_ticks(', len(audusd_ticks), ')')
for val in audusd_ticks[:10]: print(val)
print('eurusd_rates(', len(eurusd_rates), ')')
for val in eurusd_rates[:10]: print(val)
print('eurgbp_rates(', len(eurgbp_rates), ')')
for val in eurgbp_rates[:10]: print(val)
print('eurcad_rates(', len(eurcad_rates), ')')
for val in eurcad_rates[:10]: print(val)
#PLOT
# create DataFrame out of the obtained data
ticks_frame = pd.DataFrame(euraud_ticks)
# convert time in seconds into the datetime format
ticks_frame['time']=pd.to_datetime(ticks_frame['time'], unit='s')
# display ticks on the chart
plt.plot(ticks_frame['time'], ticks_frame['ask'], 'r-', label='ask')
plt.plot(ticks_frame['time'], ticks_frame['bid'], 'b-', label='bid')
# display the legends
plt.legend(loc='upper left')
# add the header
plt.title('EURAUD ticks')
# display the chart
plt.show()

Use Algorithmic Trading With Machine Learning in Python

The idea of Python machine learning in Algorithmic trading is one of the most extensive topics of this time. Here we will briefly discuss some of the methods you can apply to Python machine learning for your algorithmic trading business.

Creating and Backtesting an SMA(Simple Moving Average) Trading Strategy

The Simple Moving Average (SMA) is the average price for a particular time. It works as a technical indication and is massively used to create trading strategies. Usually, two SMAs (Shorter and Longer) are calculated to build a trading strategy.

We will build a simple crossover strategy to let the computer drill a trade when the SMA calculates for a short period and crosses above the more extended period.

 Declared Condition:

IF SMA(SHORT PERIOD) > SMA(LONG PERIOD) => BUY

IF SMA(LONG PERIOD) > SMA(SHORT PERIOD) => SELL

We will use the Python Panda library for the data frames, Requests for API calls, NumPy for arrays and Matplotlib to create plots.

Extract Data From Cloud:

First, you are required to pull the historical data of Microsoft using the API of the IEX cloud. You can use the cloud you wish; it may vary from user to user.

def get_historic_data(symbol):
    ticker = symbol
    iex_api_key = 'Tsk_30a2677082d54c7b8697675d84baf94b'
    api_url = f'https://sandbox.iexapis.com/stable/stock/{ticker}/chart/max?token={iex_api_key}'
    df = requests.get(api_url).json()
    date = []
    open = []
    high = []
    low = []
    close = []
    for i in range(len(df)):
        date.append(df[i]['date'])
        open.append(df[i]['open'])
        high.append(df[i]['high'])
        low.append(df[i]['low'])
        close.append(df[i]['close'])
    date_df = pd.DataFrame(date).rename(columns = {0:'date'})
    open_df = pd.DataFrame(open).rename(columns = {0:'open'})
    high_df = pd.DataFrame(high).rename(columns = {0:'high'})
    low_df = pd.DataFrame(low).rename(columns = {0:'low'})
    close_df = pd.DataFrame(close).rename(columns = {0:'close'})
    frames = [date_df, open_df, high_df, low_df, close_df]
    df = pd.concat(frames, axis = 1, join = 'inner')
    return df
msft = get_historic_data('MSFT')
msft = msft.set_index('date')
msft = msft[msft.index >= '2020-01-01']
msft.index = pd.to_datetime(msft.index)
msft.to_csv('msft.csv')
msft = pd.read_csv('msft.csv').set_index('date')
msft.index = pd.to_datetime(msft.index)

SMA Calculation

Now, we will calculate two SMA values, SMA 20 and SMA 50 and use these two values in the dataframe.

def sma(data, n):
    sma = data.rolling(window = n).mean()
    return pd.DataFrame(sma)
n = [20, 50]
for i in n:
    msft[f'sma_{i}'] = sma(msft['close'], i)
msft.tail()

Output 

output

 

Furthermore, if you want to learn more about the use of Python and machine learning algorithms in trading, in that case, you should look into this Multilayer Perceptron and Backpropagation Algorithm implementation in Python from a different perspective.

Summary:

The inauguration of algorithmic trading brought immense change to the financial industry. And now, with the blessing of AI and machine learning, it has opened the door to unlimited opportunities. Although Python is way more straightforward and practical than other programming languages, most trading companies and traders focus on their business using machine learning in Python.

The media shown in this article is not owned by Analytics Vidhya and are used at the Author’s discretion.



Zadhid Powell 09 May 2022

Frequently Asked Questions

Lorem ipsum dolor sit amet, consectetur adipiscing elit,

Responses From Readers

Clear