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 is a high-level language that is easy to learn and use, and has a large and active community of developers. It is particularly popular for data analysis and visualization, making it a good choice for algorithmic trading systems that rely on these functions.

Are Python trading bots worth it? ›

Thus, a trading bot built with Python can respond dynamically to market trends, executing trades based on your personalized algorithmic trading strategies. The ability to modify rules as per market volatility makes these bots a powerful tool for traders.

Can we automate trading using Python? ›

By automating your trading strategy using Python, you can save time and reduce human errors while also enabling you to test and backtest your strategies more easily. In this article, we'll provide a beginner's guide to automating your options trading strategy using Python, including code examples.

What is the success rate of trading bots? ›

In trading, success rates of 50-60% for long-term trading systems and 70-80% for intraday trading systems are considered to be good values. However, some Forex trading robots on the market claim a success rate of 95% or even higher, in which case you should be wary, because: it could be a marketing gimmick.

Is algo trading always profitable? ›

Is algo trading profitable? The answer is both yes and no. If you use the system correctly, implement the right backtesting, validation, and risk management methods, it can be profitable. However, many people don't get this entirely right and end up losing money, leading some investors to claim that it does not work.

Do people make money with algo trading? ›

The traders can trade through the Algo trading platform not just to make profits but make the trading more systematic and market liquid. Algorithmic trading uses a combination of programming and financial markets to perform trade at the right time.

Can you live off trading bots? ›

Making a living only through trading bots is obviously not easy, but it's not impossible either. While automated trading systems have helped some investors and traders earn money, it's far from easy to profit in the stock market due to the volatility of prices and market emotion.

Has anyone made a successful trading bot? ›

It depends on the bot! Some lower-risk crypto trading bots boast a 99% success rate, while others execute higher-risk strategies and have a lower success rate. The main thing most investors need to consider is whether the bot they're looking at can execute their specific investment strategy successfully.

Do AI trading bots really make money? ›

Conclusion. Trading bots have the potential to generate profits for traders by automating the trading process and capitalizing on market opportunities. However, their effectiveness depends on various factors, including market conditions, strategy effectiveness, risk management, and technology infrastructure.

Which language is best for algo trading? ›

Java remains a dominant force in the realm of algorithmic trading systems, particularly for high-frequency trading (HFT) applications. Known for its performance, scalability, and platform independence, Java is well-suited for building complex trading systems that require low latency and high throughput.

What is the best Python framework for algo trading? ›

Algorithmic trading frameworks for Python
  • AlphaPy. ...
  • bt. ...
  • AlphaLens. ...
  • PyFolio. ...
  • PyAlgoTrade. ...
  • LEAN. ...
  • FreqTrade. Freqtrade is a free and open source crypto trading bot written in Python. ...
  • Gekko. Gekko is no longer maintainer.

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.

Which language is used to create algo trading? ›

What Programming Language Do Algorithmic Traders Use? Because it is highly efficient in processing high volumes of data, C++ is a popular programming choice among algorithmic traders.

Top Articles
Latest Posts
Article information

Author: Rob Wisoky

Last Updated:

Views: 5774

Rating: 4.8 / 5 (68 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Rob Wisoky

Birthday: 1994-09-30

Address: 5789 Michel Vista, West Domenic, OR 80464-9452

Phone: +97313824072371

Job: Education Orchestrator

Hobby: Lockpicking, Crocheting, Baton twirling, Video gaming, Jogging, Whittling, Model building

Introduction: My name is Rob Wisoky, I am a smiling, helpful, encouraging, zealous, energetic, faithful, fantastic person who loves writing and wants to share my knowledge and understanding with you.