Automated Python Trading: From Idea to Execution (2024)

Automated Python Trading: From Idea to Execution (1)

By Jacques Joubert

Recently I had the privilege to attend the Python for Quants conference in London via live streaming. Each time I attend this series of lectures I try to capture one of the presentations in writing, this time, I will be writing on a lecture given by Dr. James Munro titled “Quant Strategies: from idea to execution”.

Note that while I have used his lecture for the majority of the information here, I do make changes and add my own experiences. What is written here is not endorsed by Man AHL and use your imagination to add all other disclosures you see fit.

I really enjoyed his lecture as it spoke to me as a professional that spends a lot of time backtesting different strategies. It very nicely captures the common errors in a backtesting.

In this article, we cover a rather basic trading strategy, which starts off looking attractive but as we slowly add more realistic factors, you will note how the performance decays.

The strategy is a simple 20 day moving an average crossover strategy. Example: if the current price is above the moving average then buy and hold, else go short and hold. The strategy will be named “ToyStrategy”.

The ToyStrategy will be run on the natural gas futures.

Note that on futures we will have to roll over the contracts and stitch the prices together, which is why we are using the adjusted settlement price.

Automated Python Trading: From Idea to Execution (2)

As a backtesting evangelist, I make a point of spreading the good news of the two different types of frameworks: vectorised and event driven. For this example, Dr. Munro decided on a vectorised backtester which is great for quickly prototyping a strategy but is the greater evil when it comes to accuracy and flexibility.

Steps for a vectorised backtester:

  1. Get data (Natural gas)
  2. Create your indicator (20 day SMA)
  3. Generate signals based on trading logic
  4. Generate positions held
  5. Calculate performance metrics
  6. Plot equity curve

Automated Python Trading: From Idea to Execution (3)

Automated Python Trading: From Idea to Execution (4)

Tada… Here is the first backtest with total returns of $32 million and an information ratio of 2.3.

As most things in life, when someone is trying to sell you something that is too good to be true, it probably is. At first glance, this is an awe-inspiring strategy that should be implemented right away! However, this article will walk you through some of the checks you need to perform in order to validate the strategy.

Step 1: Turn your black box into a glass box

Automated Python Trading: From Idea to Execution (5)

Now there are some strategies that implement machine learning techniques that are harder to turn into a glass box but this is not one of them. The easiest way to improve transparency is to simply plot all of the columns in our data frame.

Automated Python Trading: From Idea to Execution (6)

By doing this we can validate that our model acts as expected.

Chart 1: There are price data available for each day (There are no missing data for very large periods of time).

Chart 2: Clear that the 20 day SMA smooths out the data and that we don’t have any gaps or abnormal spikes.

Chart 3: This signal chart is different to my other backtests as it’s not simply a value where 1 represents a buy, 0 as liquidate, and -1 to go short. In this chart, we have to multiply the signal value by a multiple to generate the Position. (Not the best position sizing technique by a long shot but this is a toy strategy.)

Chart 4: represents the number of lots we are holding at any given point in time.

Chart 5: Daily returns

Step 2: Data Validation

Automated Python Trading: From Idea to Execution (7)

Next, we need to validate that we have clean data. Clean data would include the following checks:

  1. Have data for each trading day. If there are data missing then perform a forward fill.
  2. Make sure that there are no unrealistic spikes in the data. For example: if the average share price is between 400 and 300 then all of a sudden there is a spike of 4000, you will need to correct this. This also applies to when a value of 0 is inserted into your data.
  3. Double check that there are no duplicate dates in your time series
  4. Make sure that your data is adjusted for share splits and consolidations, having dividend adjusted prices is a bonus.
  5. Beware of free data sources! In my experience, free data sources have less clean data.

Make sure that the data are clean! Personally, a great deal of my time is spent getting and cleaning data. Quandl is said to be a good source and I would agree that Quandl is a good source for free data. However, given the option, I would take a paid source like Bloomberg any day!

Next, we run the following code to check that we have data for each of our trading days and that we can visually see all of our historical positions, this is also part of the glass box concept:

Automated Python Trading: From Idea to Execution (8)

In the screen shot above, you will note that the data only goes up to 2015-11-11 and I know that you can’t tell this from reading the article but I am expecting there to be data up to the 13th. To correct this Dr. Munro adds a check to his code that allows the ToyStrategy to carry on even if there is some missing data.

This fix is added by stating that the ToyStrategy only needs a minimum of 10 data points to calculate an SMA figure. "min_periods = 10”

Now run the code again and note the nothing has really changed. The ToyStrategy still has the same total return and information ratio as before.

Automated Python Trading: From Idea to Execution (9)

Step 3: Order management and position sizing

Automated Python Trading: From Idea to Execution (10)

Next, you need to validate that the ToyStrategy is implementing the correct position sizing technique and that it is meeting your expectations. In a vectorised backtester this can be a little tricky when dealing with multiple shares but the ToyStrategy is running on just 1 asset and using a vectorised methodology.

In step 2 you will note that the ToyStrategy is using real numbers to represent the number of contracts held at a point in time but this is incorrect, you can only hold an integer number of contracts.

To correct this is simple, just add the round() function.

Automated Python Trading: From Idea to Execution (11)

Again nothing has really changed and to double check that we are using whole numbers we run: print data.tail()

Automated Python Trading: From Idea to Execution (12)

Step 4: Make sure you have removed look ahead bias

Automated Python Trading: From Idea to Execution (13)

Next, it is clear that we have to look ahead bias due to the ToyStrategy basing signals on the current day’s closing price. To remedy this we need to lag the data, in this example, we do it by creating a “next position” column and then lagging the values in a new column called Position. In the code below, this is accomplished by adding “.shift(1)”.

Ouch! Here we can see the first major difference in the equity curve. Turns out that the ToyStrategy is less attractive now that it can’t look into the future.

Automated Python Trading: From Idea to Execution (14)

Step 5: Add transaction costs

Automated Python Trading: From Idea to Execution (15)

Up until now, the ToyStrategy strategy has been running without transaction fees and slippage. To add insult to injury, we have to use a very basic method to add the fees because of the vectorised methodology.

A well thought out backtest must include:

  • Slippage
  • Commissions
  • Other liquidity effects
  • Position management (risk limits)

Automated Python Trading: From Idea to Execution (16)

Somehow this strategy is still up, I don’t know how but more importantly we can see that there are no ways that we will be using this strategy going forward.

Step 6: live trading vs. simulation

Automated Python Trading: From Idea to Execution (17)

A recommended best practice is to run your simulated results hand in hand with your live trading. By doing this you have a way of searching for errors and fixing bugs.

If you are going to include your simulated results in your fund fact sheet for the public to view then it would be a very good idea to be as prudent as possible. It’s important that you don’t have massive discrepancies between the two. In fact, it’s better if your live results are marginally better than the simulation’s (Better to under promise and over deliver).

Automated Python Trading: From Idea to Execution (18)

Final remarks:

I hope this article has added value to those members of our community that are getting started with backtesting. There are two things that in my experience that make the most dramatic difference, those are:

  1. Removing look ahead bias by lagging the signals
  2. Adding transaction costs and slippage

If you know of other articles that would help others to get started then please be sure to leave a link in the comments section below.

Next Step

Python algorithmic trading has gained traction in the quant finance community as it makes it easy to build intricate statistical models with ease due to the availability of sufficient scientific libraries like Pandas, NumPy, PyAlgoTrade, Pybacktest and more.

In case you are looking to master the art of using Python to generate trading strategies, backtest, deal with time series, generate trading signals, predictive analysis and much more, you can enroll for our course on Python for Trading!

Automated Python Trading: From Idea to Execution (2024)

FAQs

Is Python enough for algo trading? ›

Python has the most comprehensive and mature ecosystem of libraries for data science, which makes it a perfect programming language for algorithmic trading. Most strategies rely on technical indicators, time series models, or machine learning algorithms, and Python is the ideal language for implementing them.

Is Python fast enough for trading? ›

Python, on the other hand, is an interpreted language, which can be slower compared to compiled languages like C++ and C#. However, with the help of libraries like NumPy and Pandas, Python can still achieve good performance for most algorithmic trading tasks.

Can we automate trading using Python? ›

We can analyze the stock market, figure out trends, develop trading strategies, and set up signals to automate stock trading – all using Python! The process of algorithmic trading using Python involves a few steps such as selecting the database, installing certain libraries, and historical data extraction.

Is Python good for trading bot? ›

Python is a popular choice for developing trading bots, thanks to its simplicity and extensive libraries like Pandas, NumPy and SciPy. These libraries enable efficient data analysis, making Python a preferred language for data-driven trading strategies.

Is R better than Python for algo trading? ›

While not as widely used as Python or Java in algorithmic trading, R offers unparalleled capabilities for quantitative analysis and modeling, making it suitable for developing sophisticated trading strategies.

Do people make money with algo trading? ›

Can You Make Money With Algorithmic Trading? Yes, it is possible to make money with algorithmic trading. Algorithmic trading can provide a more systematic and disciplined approach to trading, which can help traders to identify and execute trades more efficiently than a human trader could.

Can I master Python in 10 days? ›

Take your time and do it your own way. You can learn this stuff in 9 days or you can learn it in 90 days – it really is up to you.

Can I master Python in 2 weeks? ›

If you're looking for a general answer, here it is: Learning the Python basics may only take a few weeks. However, if you're pursuing a career as a programmer or data scientist, you can expect it to take four to twelve months to learn enough advanced Python to be job-ready.

How long does it take to learn Python for trading? ›

It is widely used by Traders, Analysts, and Researchers, and companies like Stripe and Robinhood in the finance industry. The duration to learn Python for finance ranges from one week to several months, depending on the depth of the course and your prior knowledge of Python programming and data science.

Is it legal to automate stock trading? ›

Yes, automated trading is legal, but it is subject to regulations and compliance with financial laws in the jurisdiction where it is practiced. Automated trading, also known as algorithmic trading or algo trading, involves the use of computer programs and algorithms to execute trades in financial markets.

How do you fully automate trading? ›

You need a strategy to automate the trading system. Consider the following steps:
  1. Formulate rules and conditions for order placement and execution.
  2. Decide on a platform based on the available feature list (or launch your own.)
  3. Apply your rules using platform functionality.
  4. Backtest your system. ...
  5. Start real-life trades.
Mar 15, 2023

What is the best trading bot? ›

Breaking Down The Best Crypto Trading Bots:
  • Phemex. ...
  • Shrimpy. ...
  • Coinigy. ...
  • 3Commas. ...
  • CryptoHopper. ...
  • TradeSanta. ...
  • Kryll‍ When it comes to building your own trading strategies, Kryll.io leads the market with their outstanding UI. ...
  • Gunbot. Gunbot is a highly customizable trading bot for advanced traders.

Do professional traders use bots? ›

In conclusion, bot trading is prevalent among professional traders, offering numerous benefits such as efficiency, speed, and risk management.

Do people actually make money with trading bots? ›

The general consensus seems to be that trading bots are ineffective for various reasons. To clarify, when I referred to a "trading bot," I meant either a bot that uses machine learning to identify patterns or one that employs sentiment analysis for news trends.

Is buying a trading bot worth it? ›

Yes. Crypto trading bots are profitable. However, it's not as simple as it sounds. You need a deeper understanding of how these tools work.

Which language is best for algo trading? ›

Python has the high performance NumPy/SciPy/Pandas data analysis library combination, which has gained widespread acceptance for algorithmic trading research. Further, high-performance plugins exist for access to the main relational databases, such as MySQL++ (MySQL/C++), JDBC (Java/MatLab) and MySQLdb (MySQL/Python).

Is Python good for algorithms? ›

Yes, Python is a powerful programming language that handles all aspects of algorithms very well. Python is one of the most powerful, yet accessible, programming languages in existence, and it's very good for implementing algorithms.

Is Python good for high-frequency trading? ›

Python is an excellent language for HFT because it is fast, efficient, and can handle large amounts of data. Python's simplicity and readability make it easy to write and maintain code, which is essential in the fast-paced world of HFT.

Is it possible to right a crypto trading algorithm in Python to make money? ›

Cryptocurrency and Algorithmic Trading

Luckily, with a bit of Python, you can automate trading decisions for you by implementing a trading strategy. In this Guided Project, you will take a first dive into the world of algorithmic trading by implementing a simple strategy and testing its performance.

Top Articles
Security Classifications Explained
How to Tell If Security Cameras Have Audio: 5 Easy Methods - AlfredCamera Blog
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Nfsd Web Portal
Selly Medaline
Latest Posts
Article information

Author: Gregorio Kreiger

Last Updated:

Views: 6336

Rating: 4.7 / 5 (77 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Gregorio Kreiger

Birthday: 1994-12-18

Address: 89212 Tracey Ramp, Sunside, MT 08453-0951

Phone: +9014805370218

Job: Customer Designer

Hobby: Mountain biking, Orienteering, Hiking, Sewing, Backpacking, Mushroom hunting, Backpacking

Introduction: My name is Gregorio Kreiger, I am a tender, brainy, enthusiastic, combative, agreeable, gentle, gentle person who loves writing and wants to share my knowledge and understanding with you.